C语言TXT文本导入排序后输出?
bb 70 2019/12/1 14:30
dd 50 2019/12/1 19:30
aa 100 2019/12/1 19:30
cc 92 2019/12/1 15:30
代码用了这个:https://zhidao.baidu.com/question/589205410475976485.html 展开
上次没有提及覆盖,所以直接使用rt+模式获取一次文件流,通过传参来读写。
这次你要覆盖,我把读写分开来了,枝春读和写两个函数,各自使用自己方式打开文件(r和w,具体区别你看看fopen的参数说明)。写函数是直接删除旧文件再新建文件写入,这样实现你要的覆盖效果。两个函数结束都会自己关闭文件流(fclose),这样更符合项目中调用。
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define PATH "c:\\rang.txt"//文件地址
typedef struct stt
{
char c1[9];
int c2;
char ymd[11];
char hhms[6];
struct stt *next;
}STT;
void readFile();
void writeFile();
void printfSTT();//打猛宏耐印链表
void px();//将链表按c2降序排列
STT *sttHead=NULL,*sttTail=NULL;
int main()
{
sttHead=(STT *)malloc(sizeof(STT));
sttHead->next=NULL;
readFile();
printfSTT();
px();
printf("-----------排序后-------------\n");
printfSTT();
writeFile();
return 0;
}
void px()
{
STT *sttHeadSave1=sttHead,*sttHeadSave2=NULL,sttSave,*nextSave;
while(sttHeadSave1->next!=NULL)
{
sttHeadSave2=sttHeadSave1->next;
while(sttHeadSave2->next!=NULL)
{
if((sttHeadSave1->next->c2)<(sttHeadSave2->next->c2))
{
sttSave=*(sttHeadSave1->next);
nextSave=sttHeadSave1->next->next;
绝绝 *(sttHeadSave1->next)=*(sttHeadSave2->next);
sttHeadSave1->next->next=nextSave;
nextSave=sttHeadSave2->next->next;
*(sttHeadSave2->next)=sttSave;
sttHeadSave2->next->next=nextSave;
}
sttHeadSave2=sttHeadSave2->next;
}
sttHeadSave1=sttHeadSave1->next;
}
}
void printfSTT()
{
STT *sttHeadSave=sttHead;
printf("-----------打印链表-------------\n");
while(sttHeadSave->next!=NULL)
{
printf("%s %d %s %s\n",sttHeadSave->next->c1,sttHeadSave->next->c2,sttHeadSave->next->ymd,sttHeadSave->next->hhms);
sttHeadSave=sttHeadSave->next;
}
}
void readFile()
{
int c2;
FILE *fp=NULL;
char c1[9],ymd[11],hhms[6];;
STT *sttNew;
if((fp=fopen(PATH,"r"))==NULL)
{
printf("can't open File!");
exit(1);
}
fseek(fp,0,SEEK_SET);
printf("-----------读取文件到链表-------------\n");
while(fscanf(fp,"%s %d %s %s",c1,&c2,ymd,hhms)!=-1)
{
sttNew=(STT *)malloc(sizeof(STT));
sttNew->next=NULL;
strcpy(sttNew->c1,c1);
sttNew->c2=c2;
strcpy(sttNew->ymd,ymd);
strcpy(sttNew->hhms,hhms);
if(sttHead->next==NULL)
sttHead->next=sttNew;
else
sttTail->next=sttNew;
sttTail=sttNew;
}
fclose(fp);
}
void writeFile()
{
FILE *fp=NULL;
if((fp=fopen(PATH,"w"))==NULL)
{
printf("can't open File!");
exit(1);
}
fseek(fp, 0, SEEK_SET);
fseek(fp, 0, SEEK_END);
printf("-----------开始写入文件-------------\n");
STT *sttHeadSave=sttHead;
fprintf(fp,"%s","-----------排序后-------------\n");
while(sttHeadSave->next!=NULL)
{
fprintf(fp,"%s %d %s %s%s",sttHeadSave->next->c1,sttHeadSave->next->c2,sttHeadSave->next->ymd,sttHeadSave->next->hhms,"\n");
sttHeadSave=sttHeadSave->next;
}
printf("------------写入完成-------------\n");
fclose(fp);
}