从C中的文件读取字符串 [英] Read string from file in C

查看:118
本文介绍了从C中的文件读取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多个字符串的文件,每个字符串在一个单独的行。所有的字符串都是32个字符(最后33个'\\\
')。

我想读取所有的字符串。现在,我只想读取它们,而不是像下面这样存储它们:

  char line [32]; 
while(!feof(fp)){
fgets(line,32,fp);
}
printf(%s,line);

打印出零。为什么不工作?



此外,我试图在每个字符串读取结束时存储一个空终止符。我改变了数组的长度为 33 ,但是如果'\\找到\\ n',用 \ 0 替换它并存储它?

行之后的 / $> feof()返回true。 code>只会在 后返回true,因为您已经尝试过并且无法读取文件的结尾。这意味着<!c $ c> while(!feof(fp))通常是不正确的 - 你应该直到读取函数失败 - 使用 feof() / ferror()来区分文件结束和其他类型的失败需要)。所以,你的代码可能看起来像:

  char line [34]; 

while(fgets(line,34,fp)!= NULL){
printf(%s,line);



$ b如果你想找到第一个'\在中加入n'字符,并用'\ 0'替换可以从< string.h> 使用 strchr()

  char * p; 

p = strchr(line,'\\\
');
if(p!= NULL)
* p ='\0';


I have a file with multiple strings, each string on a separate line. All strings are 32 character long (so 33 with the '\n' at the end).

I am trying to read all the strings. For now, I just want to read them and not store them as follows:

char line[32];
while (!feof(fp)) {
    fgets(line, 32, fp);
}
printf("%s", line);

This prints out zero. Why isn't it working?

Furthermore, I am trying to store a null terminator at the end of each string read. I changed the line array to length 33 but how would I make it that if '\n' is found, replace it with \0 and store that?

解决方案

You code isn't working because you are only allocating space for lines of 30 characters plus a newline and a null terminator, and because you are only printing out one line after feof() returns true.

Additionally, feof() returns true only after you have tried and failed to read past the end of file. This means that while (!feof(fp)) is generally incorrect - you should simply read until the reading function fails - at that point you can use feof() / ferror() to distinguish between end-of-file and other types of failures (if you need to). So, you code could look like:

char line[34];

while (fgets(line, 34, fp) != NULL) {
    printf("%s", line);
}

If you wish to find the first '\n' character in line, and replace it with '\0', you can use strchr() from <string.h>:

char *p;

p = strchr(line, '\n');
if (p != NULL)
    *p = '\0';

这篇关于从C中的文件读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆