【问题标题】:File I/O - Displaying contents of a file文件 I/O - 显示文件的内容
【发布时间】:2016-05-04 21:27:08
【问题描述】:

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

【问题讨论】:

  • 您正在尝试从以只写方式打开的文件描述符进行读取。

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


【解决方案1】:

如果您打开文件仅用于写入,则无法读取文件:

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

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

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

更新:

请注意,读取不一定以空值终止字符串!使用 cnt 而不是 strlen(buffer) 进行写入 - 但之前检查它是否

【讨论】:

  • 谢谢!还修复了尺寸!
  • 抱歉,电脑有问题。
猜你喜欢
  • 2012-05-01
  • 2010-12-25
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2013-09-22
相关资源
最近更新 更多