I am reading some C text at the address: https://cs.senecac.on.ca/~btp100/pages/content/files.html
in the section "OPENING A FILE", the author wrote:
""r+" - opens the file for reading and possibly writing".
I dont understand why the author said "possibly writing". Why not "reading and writing". are there some cases we cannot write to file if using "r+"?
It's poor wording. It should be:
r+
Open file for update (reading and writing).
When you open a file with "r+" then the file is open for reading and writing BUT the file must exist first. If you open it with "w" then the file will be created so it does not need to exist. Hope that helps.
Of course, there are some writing into a file which can fail (think of a "disk is full" situation).
The "possible writing" phrase means just that a FILE* handle fopen-ed with "r+" might be used without any write operations. For instance, if your application want to overwrite some part of the file only under some circumstances, it can avoid the writing.
Related
I have a save file containing a stream of program events. The program may read the file and execute the events to restore a previous state (say between program invocations). After that any new events are appended to this file.
I could open the file once as read-write (fopen rw), not exposing the usage pattern.
But I wonder if there are any benefits of opening it as read-only at first (fopen r) and later re-opening it as append (freopen a). Would there be any appearent difference?
In your case there may not be any specific benefits, but primary use of freopen is to change the file associated with standard text stream (stdin, stdout, stderr). It may effect the readability of your code if you use if on normal files. In your case you first open in read-only mode, but if you are opening the stream as output there are few things about freopen that we need to keep in mind.
On Linux, freopen may also fail and set errno to EBUSY when the kernel structure for the old file descriptor was not initialized completely before freopen was called
freopen should not be used on output streams because it ignores errors while closing the old file descriptor.
Read about freopen and possible error conditions with fclose in GNU manual: https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html#Opening-Streams
No there are no specific benefits of opening the file as Read Only and then reopening in Append mode. If you require changes in files during program execution than better if you open it in as per mode.
I am currently writing a code for school and am having problems re-opening a file after I have closed it.
test=open('test.txt','w')
.......
test.close
retest=open('test.txt','r')
this is the exact error message I am getting:
TypeError: invalid file: <_io.TextIOWrapper name='test.txt'
mode='w' encoding='cp1252'>
You need to close the file with test.close(). Without the (), test.close is not being called, just referenced, and your file is still open when you try to reopen it.
Better yet, you can use context managers, and your file will be closed automatically:
with open('test.txt', 'w') as test:
...
with open('test.txt', 'r') as retest:
...
Or better still (depending on your use case), you could use the r+ mode to open the file for reading and writing at the same time:
with open('test.txt', 'r+') as test:
# read and write to file as necessary
Anyway, using with open(filename, mode) as file: is more efficient since you can get rid of file.close().
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.
How do I close a file and remove it?
I have the following code:
FILE *filePtr = fopen("fileName", "w");
...
Now I want to close filePtr and remove the file "fileName".
Should I:
fclose(filePtr);
remove("fileName");
Or:
remove("fileName");
fclose(filePtr);
Does it matter which I do first?
Thanks!!
That is OS-dependent. On *nix, deleting an open file leaves it open and the data on disk, but removes the filename from the filesystem, and actually deletes the file on close; some other operating systems may not let you delete an open file at all. Therefore the former is recommended for maximum portability.
It makes more sense to fclose and then unlink.
As man unlink(2) says (for Unix systems) :
The unlink() function removes the link
named by path from its directory and
decrements the link count of the file
which was referenced by the link. If
that decrement reduces the link count
of the file to zero, and no process
has the file open, then all resources
associated with the file are
reclaimed. If one or more process
have the file open when the last link
is removed, the link is removed, but
the removal of the file is delayed
until all references to it have been
closed.
So the order doesn't matter at all.
You do not need to fopen a file to remove it. But, in linux, if you remove an fopened file, it will be deleted only after closing it. You can still read/write to it.
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.