C语言向文本中插入数据

[f@pc-lzs MyTest]$ cat data.dat
000000012, 3 
000000023, 1 
000000123, 1 
000000124, 5 
[f@pc-lzs MyTest]$ ./test
[f@pc-lzs MyTest]$ cat data.dat
000000001, 5 
000000012, 3 
000000023, 6 
000000080, 10 
000000123, 1 
000000124, 5 
000000255, 2 

C/C++ code
   
   

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

#define DATAFILE "data.dat"
#define TMPFILE "tmp.dat"

int InsertData( long code, long count)
{
FILE
* pCur, * pTmp;
long lBarCode = 0 ;
long lCount = 0 ;
char bFound = 0 ;
char cmpRet = 0 ;
char * buf = NULL;

pCur
= fopen(DATAFILE, " r " );
pTmp
= fopen(TMPFILE, " w " );

while ( ! feof(pCur) && ! bFound)
{
fscanf(pCur,
" %ld, %ld /n " , & lBarCode, & lCount);
if (lBarCode > code) // 当前行比写入行大
{
fprintf(pTmp,
" %09ld, %ld /n " , code, count); // 写入数据
fprintf(pTmp, " %09ld, %ld /n " , lBarCode, lCount); // 写入原数据
bFound = 1 ;
}
else if (lBarCode == code) // 当前行与写入行一样
{
fprintf(pTmp,
" %09ld, %ld /n " , code, count); // 写入数据即替换原来的
bFound = 1 ;
}
else // 当前行比写入行小
{
fprintf(pTmp,
" %09ld, %ld /n " , lBarCode, lCount); // 写入原数据
}
}

if (bFound) // 如果找到了把原文件后面的内容拷贝到临时文件里
{
buf
= malloc( 1024 );
while ( ! feof(pCur))
{
lCount
= fread(buf, 1 , 1024 , pCur);
fwrite(buf,
1 , lCount, pTmp);
}
}
else // 没找到的话就写在最后面
{
fprintf(pTmp,
" %09ld, %ld /n " , code, count); // 写入数据
}

fclose(pCur);
fclose(pTmp);

remove(DATAFILE);
// 删除原文件,改文件名
rename(TMPFILE, DATAFILE);

free(buf);

return 0 ;
}

int main( void )
{
InsertData(
1 , 5 );
InsertData(
23 , 6 );
InsertData(
80 , 9 );
InsertData(
255 , 2 );
InsertData(
80 , 10 );

return 0 ;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值