How to properly append lines to already existing file - c

I looked over the internet trying to find a solution for writing line by line into a file in c. I found solutions like changing the mode of fopen() to w+, wt, wb but it did not work for me. I even read to put \r instead of \n in the end of the line but still when I try to write to the file the only thing that is written there is the last line.
FILE *log = NULL;
log = fopen(fileName, "w");
if (log == NULL)
{
printf("Error! can't open log file.");
return -1;
}
fprintf(log, "you bought %s\n", pro[item].name);
fclose(log);
Many thanks for your time and help.

It is because everytime you execute fprintf in "w" mode, the log gets overwritten with the new contents as the file was not opened in the 'append' mode but in 'write' mode.
Better thing would be to use:
fopen("filename", "a");

If I understood your problem correctly, you can have two approaches,
Case 1 (Opening / closing multiple times, write one value at a time)
You need to open the file in append mode to preserve the previous content. Check the man page of fopen() for a or append mode.
Case 2 (Opening / Closing once, writing all the values at a stretch)
you need to put the fprintf() statement in some kind of loop to get all the elements printed, i.e., the index (item) value goes from 0 to some max value.

Related

How to count number of logins in C language

Well I'm making a program that initially asks to login or register.
I need to make a counter for each time the program is accessed (after the login).
C language using the array of functions and file Login Register
The method to log in and register follows the one up.
My thing is due to the lifetime of the var, because I know the moment the program ends the var just restarts.
So far I tried many ways. By macros but once again soon as the program ends it restarts.
I'm starting now to make one saving in files.
I started just now so the function is very simple, but since I only have more 2 hours to deliver the work so I hope you guys help me.
Simple function:
At the definition of fp you should call the function fopen. From the documentation of fopen:
w+
Open for reading and writing. The file is created if it
does not exist, otherwise it is truncated. The stream is
positioned at the beginning of the file.
The file gets truncated and you need to read it before you open it for writing.
fp = fopen("contador.txt", "r");
if (!fp) {
perror("fopen");
return -1;
}
fscanf(fp, "%d", &contador);
fclose(fp);
fp = fopen("contador.txt", "w");
You can use fscanf for parsing the file and storing the value into your variable.

Completely close a file in c

I need to read, and then write to a file. I don't want to use "r+" because I completely overwrite it anyway. But I am unable to completely close the file. If I try to open the file for the second time, the applications crashes (can't open). Does anyone know how to completely close the file.
And this is not the actually code, just a summary of what I want to do:
FILE* f;
fopen_s(&f, "test.txt", "r");
// read file and edit data
fclose(f);
f = 0;
fopen_s(&f, "test.txt", "w");
fprintf(f, "%c", data);
fclose(f);
fclose() closes the file. It doesn't half close it. The notion of "completely closing" a file doesn't exist. A file is either open or closed. There's no in-between.
Although in your code you're using fopen_s() to open the file. I've no idea what that function is. I assume it works like fopen(), but instead of returning a FILE pointer, it instead stores it in its argument.
So the answer to your question is: to "completely" close a file, use fclose(). As you already do. That means the problem you're having lies elsewhere.

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,"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 new a 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

C Programming fopen() while opening a file

I've been wondering about this one. Most books I've read shows that when you open a file and you found that the file is not existing, you should put an error that there's no such file then exit the system...
FILE *stream = NULL;
stream = fopen("student.txt", "rt");
if (stream==NULL) {
printf(“Cannot open input file\n”);
exit(1);
else {printf("\nReading the student list directory. Wait a moment please...");
But I thought that instead of doing that.. why not automatically create a new one when you found that the file you are opening is not existing. Even if you will not be writing on the file upon using the program (but will use it next time). I'm not sure if this is efficient or not. I'm just new here and have no programming experience whatsoever so I'm asking your opinion what are the advantages and disadvantages of creating a file upon trying to open it instead of exiting the system as usually being exampled on the books.
FILE *stream = NULL;
stream = fopen("student.txt", "rt");
if (stream == NULL) stream = fopen("student.txt", "wt");
else {
printf("\nReading the student list directory. Wait a moment please...");
Your opinion will be highly appreciated. Thank you.
Because from your example, it seems like it's an input file, if it doesn't exist, no point creating it.
For example if the program is supposed to open a file, then count how many vowels in it, then I don't see much sense of creating the file if it doesn't exist.
my $0.02 worth.
Argument mode:
``r'' Open text file for reading.
``r+'' Open for reading and writing.
``w'' Truncate file to zero length or create text file for writing.
``w+'' Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated.
``a'' Open for writing. The file is created if it does not exist.
``a+'' Open for reading and writing. The file is created if it does not
exist.
Your question is a simple case. Read above description, when you call fopen(), you should decide which mode shall be used. Please consider why a file is not created for "r" and "r+", and why a file is truncated for "w" and "w+", etc. All of these are reasonable designs.
If your program expects a file to exist and it doesn't, then creating one yourself doesn't make much sense, since it's going to be empty.
If OTOH, your program is OK with a file not existing and knows how to populate one from scratch, then it's perfectly fine to do so.
Either is fine as long as it makes sense for your program. Don't worry about efficiency here -- it's negligible. Worry about correctness first.
You may not have permission to create/write to a file in the directory that the user chooses. You will have to handle that error condition.

Seeking to beginning of file

I have a small code block that should append text to the beg of a file. However it still only adds to the end of the file. I thought the rewind set the pointer to the front of the file, thus when I added the text using fprintf it should add to the front. How can I change this?
fp = fopen("Data.txt", "a");
rewind(fp);
fprintf(fp, "%s\n", text);
fclose(fp);
Text is a char array to be added at the front of the file
1) Don't open in append mode.
When you open in append mode, all writes go to the end of the file, regardless of the seek position.
http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html
Opening a file with append mode (a as
the first character in the mode
argument) shall cause all subsequent
writes to the file to be forced to the
then current end-of-file, regardless
of intervening calls to fseek().
2) Opening without "a" still won't do what you want. It's not possible to insert into a file using the ANSI/POSIX file operations, because given the way most file systems store their data, insert is not a simple operation.
You need either to open a new file, write your new data, then append the old file afterwards, or else you need to mess around shuffling data forward in blocks. Either option is very inefficient for large files, compared with appending at the end, not to mention error-prone if you need the program or the machine to be able to unexpectedly die without corrupting data. So if this is a log file or similar, it's probably worth redesigning so that you can write new data to the end, and then reverse it all when you prepare a report from the log.
You can replace data in a file, but you can't prepend or insert it anywhere but at the very end of the file.
Just create a new file with your data and then append the old data in this file you created.

Resources