开发者

Inserting a value into a file

开发者 https://www.devze.com 2023-02-12 22:57 出处:网络
In the code below, I have saved the values 1 - 9 in an Excel file and I want to insert an \"a\" between \"4\" and \"5\". I have set the pointer开发者_如何学JAVA to position 7 but it is still inserting

In the code below, I have saved the values 1 - 9 in an Excel file and I want to insert an "a" between "4" and "5". I have set the pointer开发者_如何学JAVA to position 7 but it is still inserting it at the end. Please help me understand this.

FILE *ExcelFile = fopen("testdata.csv","a");
 if (ExcelFile == NULL)
 return -1;
 fprintf(ExcelFile,"1 2 3 4 5 6 7 8 9");
 fseek (ExcelFile, 7, SEEK_SET );
 //printf("pos is %ld bytes\n", pos);
 fprintf(ExcelFile,"a");
 fclose(ExcelFile);


The reason this does not work is because you are opening the file for appending (the "a" flag in the fopen call). Whenever you write to the file the data you write will always be appended. If your file does not exists before opening, use fopen("testdata.csv","w") instead.


You can't just "insert" the value into a file. You must open a new file, copy the first part of the first file, then your value, then the rest, and then replace the old file with the new one, or, if the file is small, read it into memory, clear the file, and then write the correct file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号