如何在C中对文件进行排序 [英] How do I sort a file in C

查看:81
本文介绍了如何在C中对文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
	struct details{
	char title[256] ;
	char platform [256];
	char score[256];
	char release_year[256];
}record[20000],temp;
int main ()
{
	int i =0,j=0,val=0;
	
  FILE * myfile;
  char a[512];
  
  myfile=fopen ("ign.txt","r");
 FILE *newFile = fopen("ign_new.txt", "w");

  if (myfile==NULL){
   perror (" empty file ");}
  else
  {
     	while ( fgets ( a, sizeof a, myfile ) != NULL ){
      
	  	switch(i) {
     

	   
   case 0  :
   	    strcpy(record[j].title,a);
    
        i++;
        break; 
	
	 case 1  :
	    
		
       strcpy(record[j].platform,a);
    
	   i++;
       break; 
	
	 case 2  :
   	     	   
         	     
        strcpy(record[j].score,a);
         
        i++;
        break; 
	
	 case 3  :
	 	strcpy(record[j].release_year,a);
       
	    i++;
        break; 
	
	 
    case 4:
	    i=0;
	    strcpy(record[j].title,a);
	    j++;
	    break;
	     
       
      
	  
	  
	  
		

}

	
	    
      
    }
    
     printf("%s",record[1].release_year);
     

    int n = j;
     
    
	for(i=1;i<n;i++){
		int flag=0;
		
		for( j=0;j<n-i;j++){
			if(atoi(record[j].score)<atoi(record[j+1].score)){
				strcpy(temp.title,record[j].title);
				strcpy(record[j].title,record[j+1].title);
				strcpy(record[j+1].title,temp.title);
				strcpy(temp.release_year,record[j].release_year);
				strcpy(record[j].release_year,record[j+1].release_year);
				strcpy(record[j+1].release_year,temp.release_year);
				strcpy(temp.platform,record[j].platform);
				strcpy(record[j].platform,record[j+1].platform);
				strcpy(record[j+1].platform,temp.platform);
				strcpy(temp.score,record[j].score);
				strcpy(record[j].score,record[j+1].score);
				strcpy(record[j+1].score,temp.score);
				flag=1;
			}
			
		}
		if(flag==0)break;
	}
       
    
    
    
    
    
    
    

    
    
    
    printf("\n %s",record[1].release_year);
    fclose (myfile);
    
  }
  return 0;
}













/ *我的文件包含18000个条目,其中一些是

title

平台

分数< br $>
release_year



140

PC

8

2013



$

无线

8

2007



1942

游戏男孩颜色

5

2000



1942

无线

5

2006

* /



我尝试了什么:



这不存储得分列的数据记录[j] .score在排序之后但是在它正确存储之前







/*my file contains 18000 entries and some of them are
title
platform
Score
release_year

140
PC
8
2013

300
Wireless
8
2007

1942
Game Boy Color
5
2000

1942
Wireless
5
2006
*/

What I have tried:

this is not storing the data of score column in record[j].score after sorting but before it is storing correctly

推荐答案

如果我是你,我会做一些功能来处理你的数据结构体。它将清理代码A LOT!我认为你将能够更容易地看到逻辑错误。以下是一些示例:
If I were you, I would do make a little set of functions to deal with your data structure. It will clean up the code A LOT! I think you will be able to see logic errors much easier. Here are some examples :
int ReadRecord( details * pd, FILE * pf )
{
    char a[512] = { 0 };
    int i = 0;
    while( ( i < 4 ) && fgets( a, sizeof a, pf ) )
    {
        if( ( a[0] == '\r' ) || ( a[0] == '\n' ) )
            continue;  // skip empty lines
        switch( i )
        {
            case 0  :
                strcpy( pd->title, a );
                break; 
            case 1  :
                strcpy( pd->platform, a );
                break; 
            case 2  :
                strcpy( pd->score, a );
                break;
            case 3  :
                strcpy( pd->release_year, a );
                break;
        }
        ++i;
    }
    return i;
}       

void CopyRecord( details *pddest, details *pdsource )
{
    strcpy( pddest->title,        pdsource->title );
    strcpy( pddest->platform,     pdsource->platform );
    strcpy( pddest->score,        pdsource->score );
    strcpy( pddest->release_year, pdsource->release_year );
}

void SwapRecords( details *pda, details *pdb )
{
    details temp = { 0 };
    CopyRecord( temp, pda );
    CopyRecord( pda, pdb );
    CopyRecord( pdb, temp );
}

int main()
{
   int j = 0;

   FILE * newFile = fopen( "ign_new.txt", "w" );
   FILE * myfile = fopen( "ign.txt", "r" );
   if( myfile == NULL )
   {
       perror (" empty file ");
       return -1;
   }

   // read the file

   while( ReadRecord( &records[j], myfile ) )
   {
       ++j;
   }

   fclose( myfile );
   myfile = NULL;

   printf( "read %d records\n", j );

   // sort the records

   int flag;
   int n = j;
   for( i = 1; i < n; i++ )
   {
      flag = 0;
      for( j = 0; j < n - i; j++ )
      {
          if( atoi( record[j].score ) < atoi( record[j+1].score ) )
          {
              SwapRecords( &record[j], &record[j+1] );
              flag = 1;
          }
      }
      if( flag == 0 )
          break;
   }

   // probably should do something with the records here
   // like write them to the new file.g

   fclose( newFile );
   return 0;
}

我建议创建一个与ReadRecord相反的WriteRecord函数,以便它们可以处理彼此的输入/输出。记得在WriteRecord中写下空白行。 ;)



顺便说一句 - 我还没有评估你的逻辑。我把它留给了你。我的观点是为处理数据结构的逻辑序列创建函数。这可以简化处理逻辑,然后你可以更清楚地看到它的内部工作原理。



一个提示 - 我认为排序中使用的for循环的术语是错了。



到底是什么。这是我如何进行排序。通常在涉及排序时,对被比较的数据实施比较功能。这是这个数据结构的一个:

I would advise making a WriteRecord function that works in reverse of the ReadRecord so that they can handle each other's input/output. Remember to write the blank line in WriteRecord. ;)

By the way - I haven't evaluated your logic. I have left that up to you. My point was to make functions for sequences of logic that deal with the data structure. This can simplify the processing logic and then you can see its inner workings much more clearly.

One hint - I think the terms of the for loops used in the sorting are wrong.

What the heck. Here's how I would do the sort. Often when sorting is involved a compare function is implemented for the data being compared. Here's one for this data structure :

int CompareRecords( details *pda, details * pdb )
{
    // return true if record a's score is less than record b's
    return atoi( pda->score ) < atoi( pdb->score );
}

现在你可以写一个这样的排序函数:

Now you can write a sort function like this :

void SortRecords( details * pd, int count )
{
    int i, j;

    for( j = 0; j < count - 1; ++j )
    {
         // The highest score record floats to the top so we don't have to check
         // the top any more -> start from the one after the outer loop index.

         for( i = j + 1; i < count; ++i )
         {
              if( CompareRecords( &pd[j], &pd[i] ) )
                  SwapRecords( &pd[j], &pd[i] );
         }
    }
}

注意 - 我根本没有尝试过这段代码。您可以尝试并调试它或使用您想要的内容。

Note - I haven't tried this code at all. You can either try it and debug it or use what you want from it.


这篇关于如何在C中对文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆