fgets 读取特定大小
我正在尝试编写一个程序,从命令行给出的文件名中读取一定数量的字符。这是我所拥有的:
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
FILE *f;
char* fileName = argv[1];
char buf[40];
f = fopen(fileName, "r");
while(!feof(f)){
fgets(buf, 10, f);
printf("%s\n", buf);
}
fclose(f);
return 1;
}
假设在这种特殊情况下我需要前 10 个字符,然后是接下来的 10 个字符,依此类推,直到文件结束。然而,当我运行这段代码时,它实际上并没有给我正确的输出。我也尝试了 11,因为文档说 fgets() 读取 n-1 个字符,但这也不起作用。一开始读了一些东西,但后来什么也没有读,它只是给了我一堆空白。知道出了什么问题吗?
谢谢
I'm trying to write a program that reads a certain amount of characters from a file name given from command line. Here is what I have:
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
FILE *f;
char* fileName = argv[1];
char buf[40];
f = fopen(fileName, "r");
while(!feof(f)){
fgets(buf, 10, f);
printf("%s\n", buf);
}
fclose(f);
return 1;
}
Say in this particular case I need first 10 chars, then the next 10 chars, etc until the file is over. However, when I run this code it doesn't actually give me the right output. I tried 11 as well since the documentation said fgets() reads n-1 characters, but that doesn't work either. Some stuff at the beginning is read, but nothing afterwards is and it just gives me a bunch of blanks. Any idea what is wrong?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找的函数是
fread
,如下所示:The function you are looking for is
fread
, like this:如果您从
printf
格式字符串中删除\n
(假设您想基本上按原样回显整个文件),它几乎可以正常工作。我还会基于
fgets(...) != NULL
进行循环,因为feof()
将在 fgets 之后 返回一个真值 错误并命中 EOF,因此最后一个缓冲区已满的内容将被打印两次。您可以对代码进行一些小的更改,如下所示:另外,正如其他人所说,虽然我花了太长时间来回答,但
fread
可能是更好的选择,因为fgets
赢了不一定要读 10 个字符;它会在每个换行符处停止,并且您不关心一次读取一行。It works almost ok if you remove the
\n
from yourprintf
format string (assuming that you want to basically echo a whole file as is).I would also loop based on
fgets(...) != NULL
sincefeof()
will return a true value afterfgets
errors and hits EOF, so your last buffer-full will be printed twice. You could make a small change to your code as so:Also, as others have stated, while I took too long to answer,
fread
may be a better alternative sincefgets
won't necessarily read 10 chars; it'll stop at every newline and you don't care about reading a line at a time.fgets
旨在读取一行,直到最大长度。如果您想一次读取 10 个字符,无论换行如何,您可能需要使用fread
来代替:无论哪种方式,您肯定不想想要使用
while (!feof(f))
。你可能想要这样的东西:fgets
is intended to read a line, up to a maximum length. If you want to read 10 characters at a time, regardless of line breaks, you probably want to usefread
instead:Either way, you definitely do not want to use
while (!feof(f))
. You probably want something like: