<分区>
我正在尝试编写一个程序来读取所有 TXT 文件并将其复制到一个特定的数组中。但是,问题是空白字符。如果我使用 fscanf,我无法将所有 TXT 文件放入一个数组中。如何将 TXT 文件复制到字符数组中?
<分区>
我正在尝试编写一个程序来读取所有 TXT 文件并将其复制到一个特定的数组中。但是,问题是空白字符。如果我使用 fscanf,我无法将所有 TXT 文件放入一个数组中。如何将 TXT 文件复制到字符数组中?
最佳答案
标准库提供了能够在一次函数调用中读取文件的全部内容所需的所有函数。您必须先计算出文件的大小,确保分配足够的内存来保存文件的内容,然后在一个函数调用中读取所有内容。
#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);
}
}
}
关于c - C语言读取一个TXT文件中的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514171/