首页 > 解决方案 > 如何将多个 .txt 文件读入单个缓冲区?

问题描述

我正在尝试将多个文本文件读入 C 中的单个 char* 数组。我可以将 char* 分配到正确的大小(即所有文本文件的大小总和)。

我尝试将每个文件一个一个地读取到它们自己的缓冲区中,然后将该缓冲区连接到包含所有文件的缓冲区的末尾。这一切都是在一个 for 循环中完成的。但是当我打印出来以确保它有效时,只有最后一个读取的文件被打印出来。

我也尝试过 fread,但这似乎覆盖了它写入的缓冲区,而不是附加到它的末尾。

这是我的代码,其中大部分来自另一个 SO 线程:

for(int i = 2; i < argc; i++) {
char *buffer = NULL;
size_t size = 0;

/* Get the buffer size */
fseek(file, 0, SEEK_END); /* Go to end of file */
size = ftell(file); /* How many bytes did we pass ? */
/* Set position of stream to the beginning */
rewind(file);
/* Allocate the buffer (no need to initialize it with calloc) */
buffer = malloc((size + 1) * sizeof(*buffer)); /* size + 1 byte for the \0 */
/* Read the file into the buffer */
fread(buffer, size, 1, file); /* Read 1 chunk of size bytes from fp into buffer */
/* NULL-terminate the buffer */
buffer[size] = '\0';

allFiles = strcat(allFiles, buffer);
free(buffer);
fclose(file);
}

请帮帮我,我被 C 语言中看似简单的事情难住了。谢谢。

标签: carrays

解决方案


听起来您所做的一切都是正确的,但是您需要在将指针传递给fread下一个文件之前递增指针,否则您将一遍又一遍地覆盖文件的开头。

假设buf所有文件的正确大小为 nul 字节 +1,并且 files 是一个char *包含文件名 long 的 '数组NUM_FILES,你需要做这样的事情。

char *p = buf;
for(int i = 0; i < NUM_FILES; i++) {
    FILE *f = fopen(files[i], "rb");

    fseek(f, 0, SEEK_END);
    long bytes = ftell(f);
    fseek(f, 0, SEEK_SET);

    fread(p, (size_t)bytes, 1, f);
    p += bytes;

    fclose(f);
}
*p = 0;

推荐阅读