Why string is not being written to file here - file

I am trying following code:
public static void main(){
var file = FileStream.open("string.txt", "rw");
assert (file != null);
try{
file.puts (new DateTime.now_local ().to_string ());
file.putc ('\n');
file.flush();
} catch(Error e){
print("Error occurred while writing.");
}
}
Above code compiles all right and also runs without any error. However, no change is being made to the "string.txt" file. Where is the error and how can it be corrected?

The problem is here:
var file = FileStream.open("string.txt", "rw");
You open the file with a mode of "rw". That is not a valid mode, see the documentation at: https://valadoc.org/glib-2.0/GLib.FileStream.open.html
Mode is used to determine the file access mode.
Mode: Meaning: Explanation: File already exists: File does not exist:
"r" read Open a file for reading read from start failure to open
"w" write Create a file for writing destroy contents create new
"a" append Append to a file write to end create new
"r+" read extended Open a file for read/write read from start error
"w+" write extended Create a file for read/write destroy contents create new
"a+" append extended Open a file for read/write write to end create new
You can use "w" for writing or "w+" for reading and writing, the same with "a" and "a+" will preserve the existing file and write to the end.

The simple answer is to use w+ instead of rw:
var file = FileStream.open("string.txt", "w+");
The documentation for Filestream.open gives a table of the accepted access modes.
If the file doesn't exist for r mode, which rw seems to be truncated too, then the file fails to open and the assertion fails for me. Also Filestream.open doesn't throw any exceptions so there's a warning about an unreachable catch clause. You may want to look GIO's IOStream if you're wanting to write input/output code that integrates with GLib's main loop for asynchronous code.

Related

fprintf() function in C is not working properly

I wrote this code to input a number from a user and output it to a file .But its is not working ,after running the code the output.txt file is still empty.
Please tell me where I have done wrong .
I assure that I have created the output.txt file before running the program so the
file pointer will not be NULL.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE *ptr;ptr=fopen("output.txt","rw");
if(ptr==NULL){printf("Error in oppening file aborting .......");exit(0);}
char ch[100];
scanf("%s",ch);
fprintf(ptr,"%s",ch);
fclose(ptr);
return 0;
}
From fopen documentation, the supported access modes are:
"r" read: Open file for input operations. The file must exist.
"w" write: Create an empty file for output operations. If a file with
the same name already exists, its contents are discarded and the file
is treated as a new empty file.
"a" append: Open file for output at the end of a file. Output
operations always write data at the end of the file, expanding it.
Repositioning operations (fseek, fsetpos, rewind) are ignored. The
file is created if it does not exist. "r+" read/update: Open a file
for update (both for input and output). The file must exist.
"w+" write/update: Create an empty file and open it for update (both
for input and output). If a file with the same name already exists its
contents are discarded and the file is treated as a new empty file.
"a+" append/update: Open a file for update (both for input and output)
with all output operations writing data at the end of the file.
Repositioning operations (fseek, fsetpos, rewind) affects the next
input operations, but output operations move the position back to the
end of file. The file is created if it does not exist.
In your code you use "rw" which is invalid and that's the reason your program doesn't work.
Change "rw" to "w" and your program will work. Note that you don't need to create output.txt, fopen will create it for you if your current user has write privileges in program's directory.

Creating a file using fopen()

I am just creating a basic file handling program.
the code is this:
#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
printf("Error",);
}
fclose(p);
}
This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success.
I am using Windows 7 and compiler is Dev C++ version 5
Change the mode argument in fopen(const char *filename, const char *mode) from:
p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0) // ^
To this:
p=fopen("D:\\TENLINES.TXT","w");//this will create a file for writing.
if(p==NULL) // ^ //If the file already exists, it will write over
//existing data.
If you want to add content to an existing file, you can use "a+" for the open mode.
See fopen() (for more open modes, and additional information about the fopen family of functions)
According to tutorial, fopen returns NULL when error occurs. Therefore, you should check if p equals NULL.
Also, in printf("Error",);, omit the comma after string.
Yes you should open the file in write mode.
Which creates the file . Read mode is only to read content
or else you can use "r+" for both read and write.
You should be able to open the file, but you need to make it first. Make a txt document with the name res.txt. It should be able to write your result into the text document.
<?php
$result = $variable1 . $variable2 "=" .$res ."";
echo $result;
$myfile = fopen("res.txt", "a+") or die("nope");
fwrite($myfile, $result);
fclose($myfile)
?>
fopen()
Syntax:
FILE *fp;
fp=fopen(“data.txt”,”r”);
if(fp!=NULL){
//file operations
}
It is necessary to write FILE in the uppercase. The function fopen() will open a file “data.txt”
in read mode.
The fopen() performs the following important task.
It searches the disk for opening the file.
In case the file exists, it loads the file from the disk into memory. If the file is found with huge contents then it loads the file part by part.
If the file does not exist this function returns a NULL. NULL is a macro defined character in the header file “stdio.h”. This indicates that it is unable to open file. There may be following reasons for failure of fopen() functions.
a.When the file is in protected or hidden mode.
b.The file may be used by another program.
It locates a character pointer, which points the first cha
racter of the file. Whenever a file is
opened the character pointer points to the first character of the file

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.

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