从C中的文件中读取字符串
我有一个包含多个字符串的文件,每个字符串在一个单独的行上。 所有字符串都是32个字符长(所以33个末尾有’\ n’)。
我正在尝试阅读所有字符串。 现在,我只想阅读它们而不是按如下方式存储它们:
char line[32]; while (!feof(fp)) { fgets(line, 32, fp); } printf("%s", line);
这打印出零。 为什么不工作?
此外,我试图在每个字符串读取的末尾存储一个空终止符。 我将line
数组更改为长度为33
但是如果找到'\n'
,我将如何将其替换为\0
并将其存储?
您的代码不起作用,因为您只为30个字符的行分配空格加上换行符和空终止符,并且因为您只在 feof()
返回true 后打印出一行。
此外, feof()
仅在您尝试并且无法读取文件末尾后才返回true。 这意味着while (!feof(fp))
通常是不正确的 – 你应该只读到读取函数失败 – 此时你可以使用feof()
/ ferror()
来区分文件结束和其他类型的失败(如果你需要)。 所以,你的代码看起来像:
char line[34]; while (fgets(line, 34, fp) != NULL) { printf("%s", line); }
如果你想line
找到第一个'\n'
字符,并用'\0'
替换它,你可以使用strchr()
:
char *p; p = strchr(line, '\n'); if (p != NULL) *p = '\0';
这是一个基本方法:
// create an line array of length 33 (32 characters plus space for the terminating \0) char line[33]; // read the lines from the file while (!feof(fp)) { // put the first 32 characters of the line into 'line' fgets(line, 32, fp); // put a '\0' at the end to terminate the string line[32] = '\0'; // print the result printf("%s\n", line); }
它是这样的:
char str[33]; //Remember the NULL terminator while(!feof(fp)) { fgets(str, 33, fp); printf("%s\n",str); }