排序文件的内容

时间:2014-11-28 14:07:41

标签: c file sorting

我正在尝试按名称对文件内容进行排序 这是代码

#include <iostream>
#include<string.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Contacts
{
    char name[20];
    int phone;
    char address[20];

};


int countLines(FILE * fp);
void sort_contact(int length , FILE * f);
int main(int argc, char** argv) {
    FILE *f=fopen("D:\\eman.txt","r");
    int c;
    c=countLines(f);

    printf("number of lines %d",c);


     sort_contact(c ,  f);
    return 0;
}


int countLines(FILE * fp){
    char line[80];
    int counter = 0;
    while ( fgets(line, sizeof line, fp) ){ 


        counter+=1;

    }
    return counter;
}



void sort_contact(int length , FILE * f)
    {
    //  struct Contacts  * eman [length];
        int flag;
        int i; // for loop counter
        struct Contacts con;
        struct Contacts tmp;
        struct Contacts conn;
        struct Contacts users[length];
        //f=fopen("","r";)
        //while( ( fscanf(f, "%s  %d %s ", con.name ,&con.phone,con.address) != EOF) && (length > 0)  )

        while( ( fscanf(f, "%s  %d %s ", users[length].name ,&users[length].phone,users[length].address) != EOF) && (length > 0)  )
            {
                con=users[length];
             conn=users[length--];
                flag=strcmp(con.name,conn.name);
                //length --;


            switch(flag)
            {
                case 1:
                    tmp=users[length--];
                    users[length--]=users[length];
                    users[length]=tmp;
                    break;

                case 0:
                case -1:
                break;  

            }

        length --;
        //seek(fd, 0, SEEK_END);
    }//end fo while
            fclose(f);
            f=fopen("D:\\eman.txt","+w");
            for(i=length;i>0;i--)
            {
            //  tmp=users[i];
                fprintf(f,"%s %d %s",users[i].name,users[i].phone, users[i].address);
            }
            fclose(f);



 } 

我将内容放在一个结构中,然后按名称对结构进行排序并将其再次添加到文件中 当我运行它时,文件中没有任何改变

2 个答案:

答案 0 :(得分:0)

您是否考虑过使用qsort()功能?

int compare_contact (const void * a, const void * b)
{
  Contacts* left = (Contacts*) a;
  Contacts* right = (Contacts*) b;
  return strncmp(left.name,right.name, sizeof Contacts.name);
}

qsort(pUsers, length, sizeof Contacts, compare_contact);

答案 1 :(得分:0)

// the following is a clean compile of your program
// with the algorithm logic corrected (and several other details)
// with checking of returned values from output I/O statements
// with checking of returned value from malloc and calloc
// with modification to the input and output format strings
// Note:
// 1) if the sizing of name and address fields is inadequate
//       for actual values in input file
//       then this algorithm will fail
// 2) if any line in the input file is longer than 80 chars
//       then this algorithm will fail
// 3) when reading a line from the file into pUsers[]
//       it would be far safer (and can validate format of line contents)
//       to read the line into a temporary area like: char line[80]
//       then parse the fields using something like: sscanf()
//       then malformed lines can be recognized/discarded
// suggest breaking the sort_contact() function into three functions:
// 1) read the input file into pUsers[]
// 2) sort pUsers[]
// 3) write the new file


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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Contacts
{
    char name[20];  // what if name is longer than 19 char in file
    int phone;
    char address[20]; // what if address is longer than 19 char in file
};

// prototypes
int countLines(FILE *);
void sort_contact(int, FILE *);

// place outside of any function because it could be HUGE,
// depending on input file size
// and do not want to put all that on the stack
static struct Contacts* pUsers = NULL;

int main()
{
    int lineCount = 0;
    FILE *inf=fopen("D:\\eman.txt","r");
    if ( NULL == inf )
    {
        perror( "fopen failed for read of eman.txt" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    lineCount = countLines(inf);

    if( 0 < lineCount )
    {
        printf("number of lines in input file: %d", lineCount);

        // note: using calloc removes need to terminate each string later
        if( NULL == (pUsers = calloc( lineCount, sizeof( struct Contacts ) ) ) )
        { // then calloc failed
            perror( "calloc failed for input array" );
            fclose(inf);
            exit( EXIT_FAILURE );
        }

        // implied else, malloc successful

        sort_contact(lineCount, inf);

        free( pUsers ); // cleanup
    }

    else
    {
        printf( "no lines read from input file\n" );
    }

    fclose( inf );  // cleanup

    return 0;
} // end function: main


int countLines(FILE * inf)
{
    char line[80]; // what if some line is greater than 79 characters or contains nulls?
    int counter = 0;
    while ( fgets(line, sizeof line, inf) )
    {
        counter+=1;
    } // end while

    rewind( inf ); // cleanup

    return counter;
} // end function: countLines


void sort_contact(int lineCount, FILE * inf)
{
    int i = 0;           // write loop counter
    int currentLine = 0; // read loop counter
    int retFscanf=0;     // returned value from fscanf

    int c; // outer sort loop counter
    int d; // inner sort loop counter

    struct Contacts tmp;

    // read all lines from file into pUsers array
    for( currentLine=0; currentLine < lineCount; currentLine++)
    {
        retFscanf = fscanf(inf, " %19s %d %19s", // note leading space in format string, no trailing space
              pUsers[currentLine].name ,
              &pUsers[currentLine].phone,
              pUsers[currentLine].address);
        if( 3 != retFscanf )
        { // then, fscanf failed
            perror( "fscanf failed" );
            fclose( inf );  // cleanup
            free( pUsers ); // cleanup
            exit( EXIT_FAILURE );
        }

        // implied else, fscanf successful
    } // end for

    // implement bubble sort here

    for (c = 0 ; c < ( lineCount-1 ); c++)
    { // whole array

        for (d = 0 ; d < (lineCount - c - 1); d++)
        { // current subset of whole array

            if ( 0 < (strcmp( pUsers[d].name, pUsers[d+1].name  ) ) )
            { // then, earlier name sorts after next name
                memcpy( &tmp,         &pUsers[d],   sizeof( struct Contacts) );
                memcpy( &pUsers[d],   &pUsers[d+1], sizeof( struct Contacts ));
                memcpy( &pUsers[d+1], &tmp,         sizeof( struct Contacts) );
            } // end if
        } // end for
    } // end for

    FILE * outf;
    if( NULL == (outf = fopen("D:\\eman.txt","+w") ) )
    { // then fopen failed
        perror( "fopen failed for write" );
        free( pUsers ); // cleanup
        fclose( inf );    // cleanup
        exit( EXIT_FAILURE );
    } // endif

    // implied else fopen successful

    for(i=0;i<lineCount;i++)
    {
            fprintf(outf,"%s %d %s\n",pUsers[i].name, pUsers[i].phone, pUsers[i].address);
    } // end for

    fclose( outf ); // cleanup
} // end function: sort_contact