如何显示文件内容? [英] how to display contents of a file?

查看:75
本文介绍了如何显示文件内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何显示通过C程序编写的文本文件的内容?
我正在使用GCC.
我尝试了cat命令,但它显示了一些随机符号.


这是我的代码:

//编写和读取文件

How can we display the contents of a text file written through a C program?
i am using GCC.
i tried cat command but it is displaying some random symbols.


here is my code:

//writing and reading a file

<pre lang="cs">#include<stdio.h>

int main()
{
FILE *fpr,*fpw;
int ch=1;
char ch1;
int i;
fpw = fopen ("myfile.txt","a");
do
{printf("Enter a no:");
scanf("%d",&i);
fputc(i,fpw);
printf("Want to enter more?(1/0):");
scanf("%d",&ch);
}while(ch==1);
fclose(fpw);

fpr = fopen ("myfile.txt","r");
printf("Reading file...\n");
while ((ch1= fgetc(fpr))!= EOF)
{ printf(" %d  ",ch1);
}
fclose(fpr);
return 0;
}


推荐答案

%d是十进制,不是吗?我想,您正在尝试将文件转换为数字而不只是显示它.
%d is decimal, isn''t it ? You''re trying to convert the file to numbers instead of just showing it, I think.


有关printf格式说明符的解释,您可以在这里查看: http://www.cplusplus.com/reference/clibrary/cstdio/printf/ [ ^ ].
出于良好的考虑,我将放入scanf的文档: http://www.cplusplus. com/reference/clibrary/cstdio/scanf/ [ ^ ].

最好的问候,

—MRB
For an explanation of printf''s format specifiers you can have a look here: http://www.cplusplus.com/reference/clibrary/cstdio/printf/[^].
Just for good measure I''ll throw in the documentation of scanf: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/[^].

Best Regards,

—MRB


您正在读入整数,然后尝试将它们写为字符.这意味着每个整数损失四分之三,因为一个整数占用4个字节,而一个字符仅占用1个字节.那么当您读回它时,就没有完整的值可以显示.您可能应该使用fwrite()fread()来读写整数值.有关完整的详细信息,请参见手册页.
You are reading integers in and then trying to write them out as characters. This means that three-quarters of each integer is lost, since an integer takes up 4 bytes, while a character only takes 1. Then when you read it back in you do not have the full value to display. You should probably use fwrite() and fread() to write and read integer values; see the man pages for full details.


这篇关于如何显示文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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