我想将文件读取为字符串。
我有以下代码,可以编译但无法运行。
我的想法是使用 while 循环将文件中的每个字符附加到字符串末尾,直到 EOF。
char string[50000];
FILE *file;
file = fopen("filename.txt", "r");
char buffer;
while((buffer=fgetc(file)) != EOF)
{
strcat(string, buffer);
}
最佳答案
首先尝试将 string[0]
设置为 \0
。另外,buffer
应该是 char *
并且以 null 结尾。
从 man
页面:
NAME
strcat, strncat -- concatenate strings
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
char *
strcat(char *restrict s1, const char *restrict s2);
char *
strncat(char *restrict s1, const char *restrict s2, size_t n);
DESCRIPTION
The strcat() and strncat() functions append a copy of the null-terminated
string s2 to the end of the null-terminated string s1, then add a termi-
nating `\0'. The string s1 must have sufficient space to hold the
result.
关于c - 读取文件到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313718/