文件中数据的排序有关问题


文件中数据的排序问题
在一个文件中我保存了学生的学号、班级和姓名,现在要对它们先按班级,后按学号来进行排序,
我的办法有两种:1.将数据导出到链表中,在链表中排好序,然后再导入到文件中,可我忙活了一上午,还是没弄好啊。。。
2.将数据导出到结构体数组中,可是在不知道学生人数的情况下,怎么定义结构体数组的个数了。。。。
求大神帮帮小弟啊!!
最后问下,第一种办法可行吗??

c语言 基本概念 程序开发

hyuna 14 years, 1 month ago


第一种方法当然可以。排序用冒泡就可以了(看lz的问题描述,应该是普通的作业吧)。

六分仪元渡 answered 14 years, 1 month ago


第一种当然可行
vector可以不?

人外姬阿洛 answered 14 years, 1 month ago


1,链表快速排序
2,realloc扩充数组尺寸

阿拉啦血魔 answered 14 years, 1 month ago


用第一种方法吧。

使用链表可以根据学生人数,无限扩充链表长度。

可以参考本人的这个程序。

读取new.txt的文件内容放到结构体链表里面,倒叙输出到另一个链表、。


  C/C++ code

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

struct info{
int id;
char name[10];
char sex[10];
char col[10];
char sub[15];
char marks[20];
struct info * prev;
struct info * next;
};
typedef struct info *st;
static st head = NULL;//链表头指针
#define PRINT_ST(str) \
"%d;%s;%s;%s;%s;%s\n",\
str->id,str->name, str->sex,str->col, str->sub, str->marks

int temp = 1;

int break_up(char *buffer);//分割字符串函数
int put_in(char* str[]);//放入结构体
int print_st(st str);//输出结构体,测试用
char * char_filter( char *str);//去掉行末回车符
int insert_list(st p);//插入链表

int main(void)
{
FILE *stream;
char msg[100];
char backup[100];
st p1, p2;
/* open a file for update */
stream = fopen("file.txt","r");
/* seek to the start of the file */
fseek(stream, 0, SEEK_SET);//指针指向文件头部
/*备份第一行内容*/
fgets(msg, 100, stream) != NULL;
strcpy(backup, msg);
/* 从第二行开始去数据 */
while( fgets(msg, 100, stream) != NULL)
{
printf("%s",msg);
break_up(msg);

memset(msg, 0, sizeof(msg));
}
/*先读取一行内容,测试用
  fgets(msg, 100, stream) != NULL;
  printf("%s",msg);
  break_up(msg);
  */
fclose(stream);
/*正序输出链表,测试用*/
p1 = head;
puts("\n");
while( p1 != NULL)
{
print_st(p1);
p1 = p1->next;
}
/*倒序输出链表,测试用*/
p1 = head;
puts("\n");
while(p1 != NULL)
{
p2 = p1;
p1 = p1->next;
}
while(p2 != NULL)
{
print_st(p2);
p2 = p2->prev;
}
puts("\n");


/*下面新建文件,倒叙输出到一个新文件new.txt里面*/
stream = fopen("new.txt","w+");
if(fputs(backup, stream) < 0)
{
perror("fputs error:");
}

p1 = head;
while(p1 != NULL)
{
p2 = p1;
p1 = p1->next;
}
while(p2 != NULL)
{
snprintf(msg, sizeof(msg), PRINT_ST(p2));
printf("%s",msg);
fputs(msg, stream);
p2 = p2->prev;
}

fclose(stream);

/*释放链表*/
p1 = head->next;
while (p1 != NULL)
{
p2 = p1;
p1 = p1->next;
free(p2);
}
free(head);
head = NULL;

return 0;
}
/*分割字符串*/
int break_up(char *buffer)
{
int i = 0, j = 0;

char *p[20]= {NULL};
char *buf=buffer;

char *outer_ptr=NULL;
char *inner_ptr=NULL;

while((p[i]=strtok_r(buf,";",&outer_ptr))!=NULL)
{
i++;
buf=NULL;

520520 answered 14 years, 1 month ago

Your Answer