C - 从文件中读取
C - Reading from a file
我有一个包含以下内容的文本文件:
ANT. Small insect,
sometimes has wings on its back.
BEAR. Large beast.
我有一个c程序:
int main(void)
{
FILE *fp;
int c;
fp = fopen("myfile.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
} do {
c = fgetc(fp);
if(feof(fp))
break ;
if (c != '\n')
printf("%c", c);
}while(1);
fclose(fp);
}
然而它只打印:
BEAR. Large beast.
我要它打印:
ANT. Small insect, sometimes has wings on its back.
BEAR. Large beast.
/*Everything looks find in your code. in my machine it is working fine . I have only added a if condition to print the contents same as the file thats it .. */
#include<stdio.h>
int main(void)
{
FILE *fp;
int c;
fp = fopen("rabi.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
} do {
c = fgetc(fp);
if(feof(fp))
break ;
printf("%c", c);
printf ("\n");
}while(1);
printf ("\n");
fclose(fp);
}
o/p-->
rabi@rabi-VirtualBox:~/rabi/c$ gcc 11.c
rabi@rabi-VirtualBox:~/rabi/c$ ./a.out
ANT. Small insect,
sometimes has wings on its back.
BEAR. Large beast.
在 DOS/Windows 机器上创建的文本文件与在 Unix/Linux 上创建的文件具有不同的行尾。 DOS 使用回车符 return 和换行符 ("\r\n") 作为行尾,而 Unix 仅使用换行符 ("\n")。在 Windows 机器和 Unix 机器之间传输文件时需要小心,以确保行尾被正确翻译。
我有一个包含以下内容的文本文件:
ANT. Small insect, sometimes has wings on its back. BEAR. Large beast.
我有一个c程序:
int main(void)
{
FILE *fp;
int c;
fp = fopen("myfile.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
} do {
c = fgetc(fp);
if(feof(fp))
break ;
if (c != '\n')
printf("%c", c);
}while(1);
fclose(fp);
}
然而它只打印:
BEAR. Large beast.
我要它打印:
ANT. Small insect, sometimes has wings on its back. BEAR. Large beast.
/*Everything looks find in your code. in my machine it is working fine . I have only added a if condition to print the contents same as the file thats it .. */
#include<stdio.h>
int main(void)
{
FILE *fp;
int c;
fp = fopen("rabi.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
} do {
c = fgetc(fp);
if(feof(fp))
break ;
printf("%c", c);
printf ("\n");
}while(1);
printf ("\n");
fclose(fp);
}
o/p-->
rabi@rabi-VirtualBox:~/rabi/c$ gcc 11.c
rabi@rabi-VirtualBox:~/rabi/c$ ./a.out
ANT. Small insect,
sometimes has wings on its back.
BEAR. Large beast.
在 DOS/Windows 机器上创建的文本文件与在 Unix/Linux 上创建的文件具有不同的行尾。 DOS 使用回车符 return 和换行符 ("\r\n") 作为行尾,而 Unix 仅使用换行符 ("\n")。在 Windows 机器和 Unix 机器之间传输文件时需要小心,以确保行尾被正确翻译。