如何让 fgetc 在循环内打印文件的所有字符
我正在使用 fgetc,想知道如何让我的循环打印该行部分一次,然后打印前 16 个字符。
这是我的代码:
int main(int argc, char * argv[])
{
FILE *fp;
if((fp = fopen(argv[1], "rb+")) == '\0')
{
perror("fopen");
return 0;
}
getchar(fp);
return 0;
}
void getchar(FILE *fp)
{
int c;
size_t linecount = 0;
while((c = fgetc(fp)) != EOF)
{
printf("line : ");
printf("%c ", c);
linecount++;
if(linecount == 16)
{
printf("\n");
}
}
}
我希望我的输出类似于:
line: ? 5 d s d a d 0 0 0 0 0 0 0 0 0 0 0
line: a d s x c v d 0 0 0 0 0 0 0 0
我尝试使用此 for 循环打印字符:
for(i = 0; i < 16; i++)
{
printf("%c ", c);
}
但这没有得到其他字符,因为循环仍然集中在第一个字符上
I'm playing around with fgetc and was wondering how I would get my loop to print the line section once then print the first 16 characters.
Here is my code:
int main(int argc, char * argv[])
{
FILE *fp;
if((fp = fopen(argv[1], "rb+")) == '\0')
{
perror("fopen");
return 0;
}
getchar(fp);
return 0;
}
void getchar(FILE *fp)
{
int c;
size_t linecount = 0;
while((c = fgetc(fp)) != EOF)
{
printf("line : ");
printf("%c ", c);
linecount++;
if(linecount == 16)
{
printf("\n");
}
}
}
I want my output to be something like:
line: ? 5 d s d a d 0 0 0 0 0 0 0 0 0 0 0
line: a d s x c v d 0 0 0 0 0 0 0 0
I've tried printing the characters using this for loop:
for(i = 0; i < 16; i++)
{
printf("%c ", c);
}
But that didn't get the other characters, because the loop was still concentrated on the first character
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,
中已经定义了一个名为getchar()
的标准函数 - 您必须更改函数的名称,否则您可能会得到一些非常糟糕的结果。奇怪的行为。其次,在我看来,你想做的是:
"line: "
;“\n”
。这将转换为代码形式:
Firstly, there is already a standard function called
getchar()
defined in<stdio.h>
- you must change the name of your function, or your may get some very strange behaviour.Secondly, it seems to me that what you want to do is:
"line: "
;"\n"
.This would translate into code form as:
ASCII
NUL
字符与NULL
指针不同。这应该是== NULL
或if(!(fp = fopen(argv[1], "rb+"))) /* ... */
,以两者为准你认为更容易阅读。此子句中的return 0
可能应该是return 1
,因此在标准管道中使用您的程序会更容易。 (程序中的错误通过非零返回值来明确。是的,这有点倒退,但是有 充分的理由。)哎呀。
标头中已存在getchar(3)
。重新定义它并不是一个好主意。 (它现在可能有效,但将来的修改可能会由于不明显的原因而完全失败。)我已经重新设计了
gc()
例程中的循环,它应该可以满足您的需要:自行运行时的输出:
The ASCII
NUL
character is not the same as theNULL
pointer. This should be== NULL
, orif(!(fp = fopen(argv[1], "rb+"))) /* ... */
, whichever you think is easier to read. Thereturn 0
in this clause should probably bereturn 1
, so it is easier to work with your program in standard pipelines. (Errors in programs are made clear by a non-zero return value. Yes, it's a bit backwards, but there's good reason.)Oops.
getchar(3)
already exists in the<stdio.h>
header. Redefining it is not a good idea. (It might work now, but a future modification might completely fail for non-obvious reasons.)I've re-worked the loop in the
gc()
routine a little, it should do what you need:The output when run on itself: