【问题标题】:c multiple file descriptorsc 多个文件描述符
【发布时间】:2018-08-15 20:28:34
【问题描述】:

我正在尝试制作一个将两个文件的内容连接到目标文件的 C 程序。为此,我必须同时打开至少 2 个文件,但我不知道为什么不能。这个问题可以用下面两段代码来充分描述:

为什么会这样:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>


int main(int argc, char* argv[]){
    size_t fdes = open(argv[1], O_RDONLY);
    void * buf;
    int bytes;
    while ((bytes = (int)read(fdes, buf, 3)) > 0) {
        printf("%s", (char*)buf);
    }
    close(fdes);
    return 0;
}

这不是吗?

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>


int main(int argc, char* argv[]){
    size_t fdes = open(argv[1], O_RDONLY);
    size_t fdes2 = open(argv[2], O_RDONLY);
    void * buf;
    int bytes;
    while ((bytes = (int)read(fdes, buf, 3)) > 0) {
        printf("%s", (char*)buf);
    }
    close(fdes);
    close(fdes2);
    return 0;
}

我不能打开多个文件吗?

【问题讨论】:

  • buf 未初始化,两个版本都不起作用。你只是从未定义的行为中得到了一些不同的东西。
  • 另外,open 返回 int 和 read 返回 ssize_t.. 强烈建议使用这些正确类型并在继续之前检查 open 返回代码。
  • 您没有为缓冲区分配空间(void *buffer = (char [])"   "; 可能有效,但使用char buffer[4] = ""; 会更明智)。您永远不会从第二个缓冲区中读取。你不检查任何东西是否有效(总是检查open()、fopen() 和他们的亲属返回的值),并且你不确保你有空终止的信息。您也应该在printf() 中使用bytes; printf("%.*s", bytes, (char *)buf); — 但需要强制转换表示糟糕的设计,因此建议使用 char buffer[4]。
  • 在没有先检查(使用argc)以确保用户实际输入命令行参数之前,永远不要访问argv[0]以外的地方。
  • 函数:open() 返回 int,而不是 size_t

标签: c file concatenation


【解决方案1】:

我做了一些改变,这很有效:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>


int main(int argc, char* argv[]){
    size_t fdes = open(argv[1], O_RDONLY);
    size_t fdes2 = open(argv[2], O_RDONLY);
    size_t length = 0;
    char * buf = (char *)malloc(sizeof(char) * length);
    int bytes;

    while ((bytes = (int)read(fdes, buf, sizeof(buf) - 1)) > 0) {
        printf("%s", buf);
    }

    while ((bytes = (int)read(fdes2, buf, sizeof(buf) - 1)) > 0) {
        printf("%s", buf);
    }
    close(fdes);
    close(fdes2);
    return 0;
}

首先,buf 应该是 char *

其次,您需要将buf 指向某个地方(malloc 或char array)

参考:https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/rtrea.htm

【讨论】:

  • 哎呀。 size_t length = 0; 然后malloc(sizeof(char) * length);? sizeof(char) 始终定义为 1,如果它不返回 NULL,则它是一个零字节缓冲区。鉴于char * buf,您认为sizeof(buf) 会返回什么?而read() 不会产生以NUL 结尾的字符串值。
  • 我的意思是将length 设置为0。为什么?因为程序仍然运行良好,我正在等待有人解释原因。 read() 有什么问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多