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

标签 c++ linux file-io system-calls tcpserver

我正在寻找有关简单 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] = '\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);
}

最佳答案

如果您打开文件只是为了写入,则无法读取文件:

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

如果您不想向其中写入任何内容(否则为 O_RDWR),则需要打开它进行读取,在您的情况下为 O_RDONLY。

顺便说一下 - 您的缓冲区大小是奇数 (257),通常情况下,一个人会以 2 的幂 (256) 分配缓冲区。

更新:

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

关于c++ - 文件 I/O - 显示文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37038336/

相关文章:

linux - 在 VIM 上保存文件时自动 rsync 不起作用,因为 rsync 提示密码

linux - 无法使用 hikey_defconfig 编译 u-boot

linux - 在 Linux 中从 CLI 运行 Visual Studio Code

c++ - 通过循环设计用于搜索文件的另一个函数从文件中打印出信息 - C++

c++ - C 字符串比定义的长度短一个字符?

c++ -::AddFontMemResourceEx' 尚未声明

c++ - 使用 auto 访问类的私有(private)结构

c++ - 使用来自 C++ 的 ffmpeg hwaccel

Python - 来自文件的行 - 所有组合

java - 使用Java 7 nio读写文件