Completely close a file in c - 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.

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.

How to properly append lines to already existing file

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.

live update on file /proc/<pid>/status when open

I am trying to read information from the /proc/<pid>/status file (to get the memory used).
To do this, I open the file in read mode:
file = fopen("/proc/self/status", "r");
After this step, to get the memory, I read the line that starts with "VmRSS".
My problem is this:
Each time I read this line, it's the same value, even if the file has changed.
I am doing this to get real-time memory usage of my program. So I call fopen() 1 time,
and then I call fseek() to go to the beginning of my file when I need updated information.
char line[128];
fseek(file, 0, SEEK_SET);
while (fgets(line, 128, file) != NULL)
{
//...
}
But, the file is not updated, unless I reopen it. I don't want to reopen it for performance reasons.
I tried to change "r" to "r+" (to have a "Open a file for update", according to the documentation of fopen()), but fopen returns NULL in this case.
So my question:
Do you have any idea on how my program can open a file and see changes from made by another programme (here the kernel) using only one call to fopen()?
Note :
I use Ubuntu 12.04
You need to reopen the file To avoid race conditions,
proc is a file system in memeory and most /proc content are being fixed on open.
Maybe you can open the /proc/<pid>/status file with open but not fopen.
int fd = open('/proc/<pid>/status', O_RDONLY, MYF(0));
// read
seek(fd, 0L, MY_SEEK_SET, MYF(0));
// read

clear/truncate file in C when already open in "r+" mode

My code currently looks something like this (these steps splitted into multiple functions):
/* open file */
FILE *file = fopen(filename, "r+");
if(!file) {
/* read the file */
/* modify the data */
/* truncate file (how does this work?)*/
/* write new data into file */
/* close file */
fclose(file);
}
I know I could open the file with in "w" mode, but I don't want to do this in this case. I know there is a function ftruncate in unistd.h/sys/types.h, but I don't want to use these functions my code should be highly portable (on windows too).
Is there a possibility to clear a file without closing/reopen it?
With standard C, the only way is to reopen the file in "w+" mode every time you need to truncate. You can use freopen() for this. "w+" will continue to allow reading from it, so there's no need to close and reopen yet again in "r+" mode. The semantics of "w+" are:
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.
(Taken from the fopen(3) man page.)
You can pass a NULL pointer as the filename parameter when using freopen():
my_file = freopen(NULL, "w+", my_file);
If you don't need to read from the file anymore at all, when "w" mode will also do just fine.
You can write a function something like this:(pseudo code)
if(this is linux box)
use truncate()
else if (this is windows box)
use _chsize_s()
This is the most straightforward solution for your requirement.
Refer: man truncate and _chsize_s at msdn.microsoft.com
and include necessary header files too.

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.

Resources