c语言读取未知长度的txt,C语言,用动态链表实现读取未知条数的txt文件。原代码如下,求高人修改。并讲解下实现原理。...

匿名用户

1级

2012-08-08 回答

#include "stdafx.h"

#include

#include

#include

#include

#include

#define MAX_NAME_LEN 1024 //最长名称

#define MAX_LINE_LEN 2048 //每行最长字符数

#define READ_IN_FILE_NAME "D:\\test.txt" //入力文件路径为:D:\\test.txt

#define OUT_PUT_FILE_NAME "D:\\test_sort.txt" //出力文件路径为:D:\\test_sort.txt

typedef struct

{

char pcName[MAX_NAME_LEN];

int iSex;

int iAge;

struct STRUCT_DATA * next;

}STRUCT_DATA;

int compare(const void *_pData1,const void *_pData2)

{

STRUCT_DATA *pSrcData1 = (STRUCT_DATA*)_pData1;

STRUCT_DATA *pSrcData2 = (STRUCT_DATA*)_pData2;

if(NULL == pSrcData1 || NULL == pSrcData2)

{

return 0;

}

return pSrcData1->iAge - pSrcData2->iAge;

}

struct STRUCT_DATA *head;

int iDataNum;

int main(int argc,char argv[])

{

STRUCT_DATA *pNewData, *pCurData;

FILE *pReadInFileData = NULL;

FILE *pOutputFileData = NULL;

//读取文件

pReadInFileData = fopen(READ_IN_FILE_NAME,"r");

if(pReadInFileData == NULL)

{

printf("open file fail!!!\r\n");

getch();

return -1;

}

//存入数组

char pcLine[MAX_LINE_LEN] = "";

while (fgets(pcLine,MAX_LINE_LEN,pReadInFileData) != EOF)//name sex age

{

pNewData = (STRUCT_DATA *)malloc(sizeof(STRUCT_DATA));

if(pNewData == NULL) {

fclose(pReadInFileData);

freeList(head);

getch();

return -2;

}

pNewData->next = NULL;

if(sscanf(pcLine,"%s%d%d",pNewData.pcName,&pNewData.iSex,&pNewData.iAge)!=3)

{

printf("ReadData Error!!!\r\n");

fclose(pReadInFileData);

freeList(head);

getch();

return -2;

}

if(head == NULL)

head = pNewData;

else

{

if(pNewData->iAge < head->iAge) {

pNewData->next = head;

head = pNewData;

continue;

}

for(pCurData = head; pCurData->next != NULL; pCurData = pInsertData->next)

{

if(pNewData->iAge < pCurData->next->iAge) //按升序排序

{

pNewData->next = pCurData->next;

pCurData->next = pNewData;

break;

}

}

if(pCurData->next = NULL) //最大值,插到链表结尾

pCurData->next = pNewData;

}

}

//关闭文件

fclose(pReadInFileData);

pReadInFileData=NULL;

//打开文件

pOutputFileData = fopen(OUT_PUT_FILE_NAME,"w");

if(pOutputFileData == NULL)

{

printf("open file fail!!!\r\n");

getch();

return -3;

}

//输出

printf("name\tsex\tage\t\r\n");

for(pCurData = head; pCurData != NULL; pCurData = pCurData->next)

{

sprintf(pcLine, "%s\t%d\t%d\t\r\n",pCurData->pcName,pCurData->iSex,pCurData->iAge);

getch();

fputs(pcLine,pOutputFileData);

printf(pcLine);

}

//关闭文件

fclose(pOutputFileData);

pOutputFileData=NULL;

freeList(head);

}

void freeList(STRUCT_DATA *head)

{

STRUCT_DATA *pCurData, *pNextData;

for(pCurData = head; pCurData != NULL; ) {

pNextData = pCurData->next;

free(pCurData);

pCurData = pNextData;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值