2012-11-16 70 views
2

我想將我的輸入數據文件分成兩個基於標籤的輸出文件。下面是我的代碼below.下面的代碼只適用於較少數量的記錄,但它進入分段錯誤更多的沒有。行。如何將一個文件拆分爲兩個文件的400k記錄

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

int main(int argc,char *argv[]) 
{ 
     FILE *fp,*fp1,*fp2,*fp3; 
     char *filename,line[80],line1[80]; 
     char *token,*token1,mystr[10]; 

     filename=(char *)argv[1]; 
     fp=fopen(filename,"r"); 

     if(fp ==NULL) //Checking whether the command line argument was correctly or not. 
     printf("There is no such file in the directory.\n"); 

     if(remove("sales_ok_fraud.txt") != 0) //Checking for file existence. 
     perror("Error in deleting the file.\n"); 
     else 
     printf("The existing cleansed data file is successfully deleted.\n"); 

     if(remove("sales_unknwn.txt") != 0) //Checking for file existence. 
     perror("Error in deleting the file.\n"); 
     else 
     printf("The existing cleansed data file is successfully deleted.\n"); 

     while(fgets(line,80,fp)!=NULL) //Reading each line from file to calculate the file size. 
     { 
       strcpy(line1,line); 
       token = strtok(line,","); 
       token = strtok(NULL,","); 
       token = strtok(NULL,","); 
       token = strtok(NULL,","); 
       token = strtok(NULL,","); 
       token = strtok(NULL,","); 
       token1 = strtok(token,"\n"); 
       memcpy(mystr,&token1[0],strlen(token1)-1); 
       mystr[strlen(token1)-1] = '\0'; 


       if(strcmp(mystr,"ok") == 0) 
       { 
         fp1=fopen("sales_ok_fraud.txt","a");//Opening the file in append mode. 
    fprintf(fp1,"%s",line1);//Writing into the file. 
         fclose(fp2);//Closing the file. 

         //printf("Inside ok - %s\n",mystr); 
       } 
       else if(strcmp(mystr,"fraud") == 0) 
       { 
         fp2=fopen("sales_ok_fraud.txt","a");//Opening the file in append mode. 
         fprintf(fp2,"%s",line1);//Writing into the file. 
         fclose(fp2);//Closing the file. 
         //printf("Inside fraud - %s\n",mystr); 
       } 
       else 
       { 
         fp3=fopen("sales_unknwn.txt","a");//Opening the file in append mode. 
         fprintf(fp3,"%s",line1);//Writing into the file. 
         fclose(fp3);//Closing the file. 
         //printf("This is unknown record.\n"); 
       } 
     } 

     fclose(fp); 

     return 0; 
} 

回答

2

我看到你的代碼的一些問題,首先strlen返回字符串包括空字節,所以你並不需要的長度-1(這就是爲什麼它可能不匹配任何strcmp的的)

memcpy(mystr, &token1[0], strlen(token1)); 
mystr[strlen(token1)] = '\0'; 

在這裏,我想你應該關閉fp1

fp1=fopen("sales_ok_fraud.txt","a"); //you open f1 
fprintf(fp1,"%s",line1);    //you write 
fclose(fp2);//Closing the file.  //you close fp2 

注意:您應該確保token1不會溢出mystr

+0

是的,完美的是這個bug。錯誤地關閉文件指針。 :) – Teja

+0

@SOaddict我很高興它的作品:) – iabdalkader

相關問題