Clear contents of a Text File - c

I am working on a sever/client applicataion. I want to maintain information of all active clients in a text file named "Information.txt".
I update this text file after every 3 seonds. So, I want the text file to clear all of its contents after every 3 seconds without deleting the file.
Is there any way to do it ? :(
I don't want to use freopen().

A problem with clearing the file periodically is that if your process crashes after the file has been cleared but before it has been written, you lose data: the old data is gone, but the new data is not there yet.
A common approach to this problem is to create a new file, writing it, and then moving the new file to replace the old one. This way you always have a file, and sometimes (for very brief periods of time) you have two files.

Try with
fopen(filename, flag)
Open your file with flag= "w" or "wb" and it will be cleared

Just open the file with fopen and setting the flag to w or w+ or wb
From fopen man page
w
Truncate file to zero length or create text file for writing. The
stream is positioned at the beginning of the file.
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.

Related

Append to the end of file with Write permissions

I was trying to code and ran into a problem.
FILE *tickets = fopen("tickets.h", "w"); - so here I open a file source where in the future I want to append some text to the end of the file. So the problem is that I don't want the file content to be removed and want to append text to the end of the file. I've chosen write permissions because in the future the program will be writing doing stuff with the write and not the append perms.
Help will be appreciated!
You should use FILE *tickets = fopen("tickets.h", "a");
Because when you open a file in the write mode, the file is overwritten, resulting in deletion of any data already present in the file. But in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any).

Reading a string from a file with C. Fopen with w+ mode is not working

I made a C program that reads a string from a .txt file, then it encrypts the string, and finally it writes the string in the same file.
The thing is that if I use fopen("D:\\Prueba.txt","w+"), the program doesn't work, it prints garbage like this )PHI N.
I've debugged and I know the error is there in that line, because if I use fopen("D:\\Prueba.txt","r+"), the program works, and it writes what it should.
But I want to use w+ because it will rewrite what the .txt file had. Why is w+ not working?
If you're opening with w+ to first read the content, that's not going to work. From C11:
w+: truncate to zero length or create text file for update.
What's probably happening is that you read data from the now empty file but don't correctly check that it worked. That would explain the weird "content" you see of )PHI N.
One solution is to open the file as with r, open another file with w, and transfer the contents, encrypting them as part of that process. Then close both, delete the original, and rename the new one to the original name. This will allow you to process arbitrarily-sized files since you process them a bit at a time.
If you don't want to use a temporary file, and you're sure you can store the entire content in memory, you could open it r+, get the content, the reopen it with a new mode, such as with:
FILE *readFh = fopen( "myfile.txt", "r+");
// Read in content, massage as needed.
FILE *writeFh = frepoen( NULL, "w+", readFh);
// Provided that worked, you should now have an empty file to write to.
// Write back your massaged data.

Confusion about different file modes

If I open a (say) binary file, and I want to append the end of it both of the following ways seem to work for me
fileVar = fopen("FileName", "w+b");
and
fileVar = fopen("FileName", "r+b");
I have read the documentation, but I'm not clear about the difference between these two methods of opening the file. This website says that w+ will overwrite a file if it doesn't exist already, and a+ will append to the end of the file. I haven't tried using a+, but it seems to do the same thing as r+.
Question: What exactly is the difference between the three ways of opening a file, r+, w+ and a+?
r+ starts at beginning of file, but will not create a new file if it doesn't exists.
w+ truncates existing file to zero length if the file exists, otherwise creates a new file.
a+ starts at end of file if file exists, otherwise creates a new file.
Access modes r+, w+ and a+ opens the file in read and write mode, but with the above difference:
Both r+ and w+ we can read ,write on file but r+ does not truncate (delete) the content of file as well it doesn’t create a new file if such file doesn’t exits while in w+ truncate the content of file as well as create a new file if such file doesn’t exists.
Just like the website says:
r+ will open the file for reading & writing, but the file must exist.
w+ will open the file for reading & writing, but if the file exists it will truncate the file (remove its contents).
a+ will open the file for reading & writing, but while reading is allowed at any location, you can only write to the end of the file, i.e. append.

Detecting file deletion after fopen

im working in a code that detects changes in a file (a log file) then its process the changes with the help of fseek and ftell. but if the file get deleted and changed (with logrotate) the program stops but not dies, because it not detect more changes (even if the file is recreated). fseek dont show errors and eiter ftell.
how i can detect that file deletion? maybe a way to reopen the file with other FILE *var and comparing file descriptor. but how i can do that. ?
When a file gets deleted, it is not necessarily erased from your disk. In your case the program still has a handle to the old file. The old file handle will not get you any information about its deletion or replacement with another file.
An easy way to detect file deletion and recreation is using stat(2) and fstat(2). They give you a struct stat which contains the inode for the file. When a file is recreated (and still open) the files (old open and recreated) are different and thus the inodes are different. The inode field is st_ino. Yes, you need to poll this unless you wish to use Linux-features like inotify.
You can periodically close the file and open it again, that way you will open the newly created one. Files actually get deleted when there is no handle to the file (open file descriptor is a handle), you are still holding the old file.
On windows, you could set callbacks on the modifications of the FS. Here are details: http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx

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