2017-06-14 412 views
-4

我有一個問題,我試圖從指針複製一行到文件,但有一個錯誤,說我不能比較指針的整數,任何人都可以幫助我嗎?該錯誤是在管線和ch = getc(file1);while(ch != EOF)指針和整數之間的比較

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <signal.h> 

#define GetCurrentDir getcwd //get the path of file 
#define BUFFER_LEN 1024 


int main(){ 

    char cCurrentPath[FILENAME_MAX]; //get 
    char line[BUFFER_LEN]; //get command line 
    char* argv[100];  //user command 
    char* path= "/bin/"; //set path at bin 
    char *ch; 
    char progpath[20];  //full file path 
    int argc;    //arg count 
    FILE *file1, *file2; //Files for history 
    int delete_line, count=0; //line to delete and counter 

    while(1){ 

     file1 = fopen("fileOne","w"); 
     if(GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) 
     { 
      printf("%s",cCurrentPath); 
     } 
     printf("/SimpleShell>> ");     //print shell prompt 

     if(!fgets(line, BUFFER_LEN, stdin)) 
     {      //get command and put it in line 
      break;        //if user hits CTRL+D break 
     } 
     else if(line, BUFFER_LEN, SIGQUIT){ 
      fopen("fileOne.c","r"); 
      ch = getc(file1); 
      while(ch != EOF){ 
       printf("%s",ch); 
      } 
     } 

     if(count<20) 
     { 
      fputs(argv[100] ,file1); 
     } 
     else{ 
      fclose(file1); 
      file1 = fopen("fileOne.c","r"); 
      rewind(file1);   
      file2 = fopen("repicla.c","w"); 
      ch = getc(file1); 
      while(ch != EOF){  
       ch = getc(file1);  
       if(ch != "\n"){   
        count++;    
        if(count != 20){     
         putc(ch, file2);    
        } 
       } 
      } 
      fclose(file1); 
      fclose(file2); 
      remove("fileOne.c");  
      rename("replica.c","fileOne.c");  
      fputs(argv[100] ,file1); 
     } 
+1

'getc'等返回一個'int',而不是''字符'故意! 'while(ch!= EOF){'with'char ch;'太不對了!並檢查像'fopen'等功能的結果! – Olaf

+0

您將'ch'聲明爲'char *'而不是'char' –

+1

@PatrickRoberts將'getc'的返回值存儲在'char'中是不可接受的,因爲它丟失了信息。 – melpomene

回答

2

更改的chchar *int類型。

7.21.7.5的getc功能

梗概

      #include <stdio.h>
            int getc(FILE *stream);

說明

     的 getc功能相當於 fgetc,不同之處在於,如果它被作爲一個宏實現,它 可以評估多於一次 stream多,所以該參數不應該具有副作用的表達 。

返回

     的 getc函數返回的下一個字符從輸入流由 stream指向。如果數據流處於文件結尾,則設置流的文件結束指示符,並返回 EOF。如果發生讀取錯誤,則會設置流的錯誤指示符,並返回 EOF

C 2011 Standard, Online Draft

您將需要使用%c,而不是%s打印出來ch;此外,以下將導致一個無限循環

ch = getc(file1); 
while(ch != EOF){ 
    printf("%s",ch); 
} 

,因爲你不是在循環體更新ch。將其改爲

while ((ch = getc(file1)) != EOF) 
    printf("%c", ch);