[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
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 ;
}