2016-03-07 148 views
-2

寫了這個代碼不知道爲什麼它不工作讀取整數。在命令行文件(TXT),並偶奇文件

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

int main (int argc, char *argv[]){ 

    int i=1; 
    //this is where i started loop read file.  
    for (i=1; i<argc;i++){ 

     FILE *file1 = fopen("argv[i]","r");//reading file 

     FILE *file2 = fopen("even.txt","w");//making even file 

     FILE *file3 = fopen("odd.txt","w");//odd file 
     //These are the files i am reading and writing to. 
     int nums; 

Main looping 
     while (file1 != EOF) 
     { 

      fscanf (file1,"%d",&nums); 

      nums++; 
      //adding the conditions to what i want each file to have. 

      if (num % 2 == '0'){ 
       fprintf (file2,"%d",nums); 
      } 

      //if condition fails move the numbers to the Odd file. 
      else { 
       fprintf (file3,"%d",nums); 
      } 

     //I tried the loops here but ut gave me segment error. 
     } 
    //closing all files 

    fclose (file1); 
    fclose (file2); 
    fclose (file3); 
    } 
return 0; 
} 
+2

'fopen(「argv [i]」,「r」)'嘗試打開一個名爲'argv [i]'的文件。你想做'fopen(argv [i],「r」)'而不用引號。 –

+1

'FILE *'不能與'EOF'相比較 –

+1

條件'file1!= EOF'不應該是錯誤的。如果'fopen'失敗則返回'NULL','EOF'等於'-1'。 –

回答

0

修改下面一行用integer.

if (num % 2 == '0') // This is wrong, you are comparing `int` with `character` 
{ 
    fprintf (file2,"%d",nums); 
} 

變化比較它至;

if (num % 2 == 0) // This is wrong, you are comparing `int` with `character` 
{ 
    fprintf (file2,"%d",nums); 
} 

希望這有助於。

+0

它確實幫助非常感謝你!哥哥。 –

+0

請接受它來驗證答案,以便對他人有幫助。 –

+0

Data1 = 1 2 3 4 5 6 7 8 9 10 In even File - 2 4 6 8 10 奇數文件 - 1 3 5 7 9 –