problem writing in file
FILE *ExcelFile = fopen("testdata.csv","w");
if (ExcelFile == NULL)
return -1;
fprintf(ExcelFile,"1 2 3");
fprintf(ExcelFile,"\n");
fclose(ExcelFile);
//==============================================
FILE *fa = fopen("testdata.csv","w");
if (fa == NULL)
return -1;
fseek (fa, 6 , SEEK_SET );
fprintf(ExcelFile,"开发者_StackOverflow社区a");
fclose(fa);
in the code i have write 1 2 3 in the file and also inserted '\n' (required for the program) now i want to place a after 3 like 1 2 3 a but hte problem iam facing is that my code erase all char an simply write a . help required .thanks
First of all, a CSV file should have "comma separated values", as the name indicates. So, rather than "1 2 3", you'd better have "1,2,3" or "1;2;3".
Now, there are multiple ways of opening a file : you're only using the "w" as "writing" mode. When you're in writing mode, you're erasing your file. You could use the "a" as "add" mode, which mean that everything will be put after it.
You could also :
1°) First read your file with a "r" mode and store it in memory. Then, close it.
2°) Then, open your file with a "w" mode, copy what you stored, and then make your addendum. Then, close it.
(There is a "reading and writing mode" too, check the link provided by another answer ; but this solution can easily be broken in small pieces, to have small functions doing each their part of the job).
Every time you open your file, you are opening it as a 'w' option. In C, this has a specific meaning : start writing at the beginning of the file.
For your first write of the file, this is okay, but for every subsequent write, you're overwriting your previous content.
Solution Use the 'a' attribute instead here. Like this:
FILE *fa = fopen("testdata.csv","a");
See more information about fopen here...
EDIT
Reading your comments, I understand that when you write again, the next thing starts on a new line. This is because of your initial write 1 2 3 \n
(The \n
makes a new line).
To correct this you can :
- Don't write a '\n' at all. OR
- Read the entire file first, rewrite it without the
\n
and then write your newa
and\n
You want mode "r+". Using mode "a", all writes will go to the end of the file.
You specified w
for fopen()
, which means "create the file or open for overwrite if already exists".
Therefore, your second call to fopen()
cleared the file's contents.
Use a
, for: "create the file, or append to it if already exists".
fopen (filename,"a")
a = append
精彩评论