C語言向文本中插入資料

來源:互聯網
上載者:User
[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;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.