文件I/O-显示文件的内容

File I/O - Displaying contents of a file

本文关键字:显示文件 文件      更新时间:2023-10-16

我在为一个简单的TCP服务器寻找一些关于函数的建议。

第三个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] = '';
 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 clientn";
close(connSock);
}

如果只打开文件进行写入,则无法读取文件:

fd = open(token[1], O_WRONLY); //open

如果你不想写任何东西,你需要打开它进行阅读,在你的情况下为O_RDONLY(否则为O_RDWR)。

顺便说一句,你的缓冲区大小是奇数(257),通常情况下,一个缓冲区的分配是二次方(256)。

更新:

请注意,read不一定为null终止字符串!使用cnt而不是strlen(缓冲区)进行写入,但要检查它是否<0(错误)和==0(文件结尾)。如果您的文件可以具有任意大小(例如,可能大于缓冲区),您可能希望在循环中执行此操作。