2014-09-30 75 views
0
main() 
{  
    FILE *fp;  
    char buff[255];  
    int i;  
    fp = fopen("input.txt", "r");  
    if(fp != NULL)  
    {   
     while (!feof(fp))  
     { 
     memset(buff, '\0', sizeof(buff)); 
     fgets(buff, 255, (FILE*)fp); 
     } 
     fclose(fp); 
    }  
    i=0;  
    while( buff[i]!='\0')  
    {   
     printf ("%s",buff[i]); 
     i++;  
    }  
} 
+0

你得到什麼錯誤? – 2014-09-30 04:14:51

+0

是你的文件包含確切的255個字節? – 2014-09-30 04:15:35

+0

'printf(「%s」,buff [i])'不好,因爲'buff [i]'是'char'而不是字符串。 – 2014-09-30 04:16:44

回答

0
printf ("%s",buff[i]); 

應該

printf ("%c",buff[i]); 

而且更多的好辦法是

char buffer[255]; 
while(!feof(fp)) { 
    if (fgets(buffer,255,fp)) { 
     printf("%s\n", buffer); 
    } 
} 
1

評論含while循環while (!feof(fp))和替換%s%cprintf

0
fgets can be used as below and also you need to use %c instead of %s 



int main() 
    { 

     FILE *fp; 

     char buff[255]; 

     int i; 


     fp = fopen("input.txt", "r"); 

     if(fp != NULL) 
     { 
      while(!feof(fp)) 
      { 
      memset(buff, '\0', sizeof(buff)); 
      fgets(buff, 255, (FILE*)fp); 
      puts(buff); 
      } 
      fclose(fp); 
     } 

     return 0; 

    }