0

C で名前付き Windows パイプを作成しようとしています。パイプはユーザーとサーバーによって使用されます。ユーザーは、パイプを介してランダムな int を送信します。次に、サーバーは現在のディレクトリで、受信した 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;
}
4

2 に答える 2