我正在尝试在 C 中创建一个命名的 Windows 管道。该管道由用户和服务器使用。用户通过管道发送一个随机整数。然后服务器在其当前目录中搜索一个大小大于或等于接收到的 int 的文件,然后将文件名和来自该文件的最大 100 字节发送回用户。
我的问题是我不知道如何验证目录中每个文件的大小,然后返回文件名和 100 个字节。
这是我试图用来测量文件大小的函数:
int fsize(char* file) { FILE * f = fopen(file, "r"); fseek(f, 0, SEEK_END); int len = (unsigned long)ftell(f); fclose(f); return len; }
这是“客户端”代码:
#include <stdio.h>
#include <windows.h>
#define MAXLINIE 100
int main(int argc, char* argv[]) {
char rcvMsg[100];
char sndMsg[100];
DWORD rez;
HANDLE readHandle, writeHandle;
int r = rand();
char str[15];
sprintf(str, "%d", r);
writeHandle = CreateFile("\\\\.\\PIPE\\FirstPipe", GENERIC_WRITE, FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
readHandle = CreateFile("\\\\.\\PIPE\\SecondPipe",GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
strcpy(sndMsg, r);
printf("Sending message to server: %s\n", sndMsg);
WriteFile(writeHandle, sndMsg, strlen(sndMsg), &rez, NULL);
printf("Message sent! Waiting for server to read the message!\n");
printf("Waiting for SERVER to write in the pipe...\n");
ReadFile(readHandle, rcvMsg, 100, &rez, NULL);
printf("Client revceived message: %s\n", rcvMsg);
CloseHandle(readHandle);
CloseHandle(writeHandle);
return 1;
}
这是“服务器”代码,文件解析部分除外:
>
#include <stdio.h>
#include <windows.h>
#define MAXLINIE 100
//file lenght
int fsize(char* file)
{
FILE * f = fopen(file, "r");
fseek(f, 0, SEEK_END);
int len = (unsigned long)ftell(f);
fclose(f);
return len;
}
int main(int argc, char* argv[]) {
char rcvMsg[100];
char sndMsg[100];
DWORD rez;
HANDLE readHandle, writeHandle;
readHandle = CreateNamedPipe("\\\\.\\PIPE\\FirstPipe", PIPE_ACCESS_INBOUND,
PIPE_TYPE_BYTE|PIPE_WAIT,3,0,0,0,NULL);
writeHandle = CreateNamedPipe("\\\\.\\PIPE\\SecondPipe", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_BYTE|PIPE_WAIT, 3, 0, 0, 0, NULL);
printf("Waiting for clients to connect...\n");
ConnectNamedPipe(writeHandle, NULL);
ConnectNamedPipe(readHandle, NULL);
printf("Waiting for a CLIENT to write in the pipe...\n");
ReadFile(readHandle, rcvMsg, 100, &rez, NULL);
printf("Server revceived message: %s\n", rcvMsg);
int num = atoi(rcvMsg); //the file lenght i'm looking for
//here i should process the files
strcpy(sndMsg, "File_name + 100 bytes");
printf("Server sends an answer: %s\n", sndMsg);
WriteFile(writeHandle, sndMsg, strlen(sndMsg), &rez, NULL);
printf("Waiting for client to read the message...\n");
// disconnecting and closing the handles
DisconnectNamedPipe(writeHandle);
CloseHandle(writeHandle);
DisconnectNamedPipe(readHandle);
CloseHandle(readHandle);
return 1;
}