我应该如何使用qsort指针来排序c中的第一个字符

时间:2017-03-22 00:05:38

标签: c

/* problem of qsorting
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUT "doc.txt"
#define OUTPUT "output.txt"
#define MAX_SIZE 500
typedef struct student // here I declare stuctures
{
    char name[20]; 
    int index;
    int code;
    int grade;
    char surname[20];
} student;
int cmpfunc (const void * a, const void * b) // initial part of qsort
{
   return ( *(char*)a - *(int*)b );
}

int main()
{
    int i=0, m=0;
    int number=0;
    FILE *fo; 
    FILE *fi;
    char file[]={INPUT};
    char file1[]={OUTPUT};
    fo = fopen(file, "r"); // open the file
    fi = fopen(file1, "w"); // open the file
    student *studentPtr;
    studentPtr = (student*) malloc(MAX_SIZE*sizeof(student)); 
// here I use mallocation
    if(fo == NULL || studentPtr == NULL || fi == NULL)
    {
        perror("Error");
        exit(1);
    }
    while (!feof(fo)) // reading of file
    {
        fscanf(fo,"%d %s %s %d %d",
        &studentPtr[i].index,
        studentPtr[i].name,
        studentPtr[i].surname,
        &studentPtr[i].code,
        &studentPtr[i].grade);
        i++;
    }
    i=m;
    printf("please insert a number upto 7:\n"); 
// because there are only   7 raws in the file
    scanf("%d",&number);
    m=number;
    if (number > 7)
    {
        printf("try again");
    }
    else
    {
        for(i=0;i<m;i++)
        {
            qsort(studentPtr[i].surname, 1, sizeof(char), cmpfunc); // ?
            printf("%d %s %s %d %d\n", // printing out
            studentPtr[i].index,
            studentPtr[i].name,
            studentPtr[i].surname,
            studentPtr[i].code,
            studentPtr[i].grade);
            fprintf(fi,"%d %s %s %d %d\n", // writing in the file
            studentPtr[i].index,
            studentPtr[i].name,
            studentPtr[i].surname,
            studentPtr[i].code,
            studentPtr[i].grade);
        }
    }
    free(studentPtr);
    fclose(fo);
    fclose(fi);
    return 0;
}

我只是初学者,对于明显的错误感到抱歉。 我不能正确地进行qsorting。 我将附上txt文件作为这篇文章的评论。 你能告诉我如何改变qsort的第一部分而不是傻事,之后我会尝试自己做这件事

0 个答案:

没有答案