【发布时间】:2014-03-19 17:52:35
【问题描述】:
我正在尝试编写一个程序来读取所有 TXT 文件并复制到一个特定的数组中。但是,问题是空白字符。如果我使用 fscanf,我无法将所有 TXT 文件放入一个数组中。如何将 TXT 文件复制到 char 数组中?
【问题讨论】:
我正在尝试编写一个程序来读取所有 TXT 文件并复制到一个特定的数组中。但是,问题是空白字符。如果我使用 fscanf,我无法将所有 TXT 文件放入一个数组中。如何将 TXT 文件复制到 char 数组中?
【问题讨论】:
标准库提供了在一次函数调用中读取文件全部内容所需的所有函数。您必须首先确定文件的大小,确保分配足够的内存来保存文件的内容,然后在一个函数调用中读取所有内容。
#include <stdio.h>
#include <stdlib.h>
long getFileSize(FILE* fp)
{
long size = 0;
fpos_t pos;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
return size;
}
int main(int argc, char** argv)
{
long fileSize;
char* fileContents;
if ( argc > 1 )
{
char* file = argv[1];
FILE* fp = fopen(file, "r");
if ( fp != NULL )
{
/* Determine the size of the file */
fileSize = getFileSize(fp);
/* Allocate memory for the contents */
fileContents = malloc(fileSize+1);
/* Read the contents */
fread(fileContents, 1, fileSize, fp);
/* fread does not automatically add a terminating NULL character.
You must add it yourself. */
fileContents[fileSize] = '\0';
/* Do something useful with the contents of the file */
printf("The contents of the file...\n%s", fileContents);
/* Release allocated memory */
free(fileContents);
fclose(fp);
}
}
}
【讨论】:
您可以使用fread(3) 从这样的流中读取所有内容:
char buf[1024];
while (fread(buf, 1, sizeof(buf), stream) > 0) {
/* put contents of buf to your array */
}
【讨论】:
你可以使用函数fgetc(<file pointer>)返回从文件中读取的单个字符,如果你使用这个函数你应该检查读取的字符是否是EOF
【讨论】: