シンプルなTCPサーバーの機能に関するアドバイスを探していました。ファイルI/O - ファイルの内容を表示
第3のif
ステートメントは、token[1]
がファイルまたはディレクトリ(これは正常に動作しています)の名前であるかどうかを確認することを想定しています。私の問題は、ファイルを開いて、クライアントのファイルの内容を表示し、ファイルを閉じることです。私はファイルI/O呼び出しを使用しようとしましたが、そのようにする方法はありませんでした。アドバイスをいただければ幸いです。
void processClientRequest(int connSock) {
int received, count = 0;
char *token[] = { (char*)0, (char*)0 };
char path[257], buffer[257];
// read a message from the client
if ((received = read(connSock, path, 256)) < 0) {
perror("receive");
exit(EXIT_FAILURE);
}
path[received] = '\0';
cerr << "received: " << path << endl;
for(char *p = strtok(path, " "); p; p = strtok(NULL, " ")) //sets tokens
token[count++] = p;
if(strcmp(token[0], "GET") != 0) { //if the first "command" was not GET, exit
strcat(buffer, "Must start with GET");
write(connSock, buffer, strlen(buffer));
exit(-1);
}
int rs;
int fd, cnt;
struct stat bufferS;
rs = stat(token[1], &bufferS);
if (S_ISREG(bufferS.st_mode)) { //input was a file
fd = open(token[1], O_WRONLY); //open
cnt = read(fd, buffer, 257); //read
write(connSock, buffer, strlen(buffer));
}
// else, open directory and stuff (code for that has been omitted to save space)
cerr << "done with this client\n";
close(connSock);
}
書き込み専用として開いているファイルディスクリプタからの読み取りを試みています。 – mausik