C - 从文件中读取

时间:2015-06-19 05:29:16

标签: c file fgetc

我有一个包含以下内容的文本文件:

ANT. Small insect,  
sometimes has wings on its back.

BEAR. Large beast.

我有一个c程序:

(n-k)/2

然而它只打印:

BEAR. Large beast.

我想要打印:

ANT. Small insect, sometimes has wings on its back.  
BEAR. Large beast.

2 个答案:

答案 0 :(得分:2)

在DOS / Windows计算机上创建的文本文件与在Unix / Linux上创建的文件具有不同的行结尾。 DOS使用回车符和换行符(“\ r \ n”)作为行结尾,Unix只使用换行符(“\ n”)。您需要注意在Windows机器和Unix机器之间传输文件,以确保正确转换行结束。

<强> Read More

答案 1 :(得分:0)

/*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.