Creating a file using fopen() - c

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

Related

Why string is not being written to file here

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.

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.

How do you get rid of file contents without the filename?

I have a function that takes in a file pointer (FILE * file) and copies everything in that file. Now, is it possible to erase everything inside this file?
I do not have the file name so I can not use fopen(filename, "w") again.
I have stdio.h and string.h included.
You can use the ftruncate() system call to empty a file using its file descriptor, e.g.
ftruncate(fileno(fh), 0);
You will probably want to follow that up with a call to rewind(fh) so that any further writes to the file are made at the beginning, rather than at the previous offset.

Opening a file in C in write mode

I am writing a C program that converts a text file into a binary file and vice versa. The first question I have is about opening a file in "w" mode. Is there any need to have a check that the output file is opened correctly?
FILE *output;
output = fopen("output.bin", "w");
if(output == NULL)
{ printf("Error opening output file\n");}
Basically my question is whether or not output would ever actually == NULL. Because if there was a problem opening the output wouldn't it just create a new file named "output.bin"?
Also my other question is how characters are actually saved in a binary file. I know I'm supposed to save each character as an unsigned char so it can have values between 0 and 255 and then I should write that char to the output file. The actual logical path of how that happens is not making sense if anyone can help me or point me in the right direction I would appreciate it!
Yes, opening a file in write mode might still fail. Here's a bunch of possible reasons, but certainly not the only ones:
You don't have permission to create or change the file.
The file is read-only, or the directory it would be in is read-only.
The file would be inside another file. (test/foo if test is a file and not a directory)
The filesystem is out of space or inodes (on filesystems that have a fixed number of inodes)
The user has hit their disk space quota.
The file would be on another computer, and the network is down.
The filename is invalid - such as C:/???*\\\\foo on windows.
The filename is too long.

query regarding writing in a file using c

Assume that the files are .txt
Contents of first file
hello how are you
Contents of second file
I am fine
The desired result is
hello how are you I am fine
Normally what happens is that the original contents are removed and then new contents are added in it.
I want to write in the first file in such a way that its original contents are maintained and the contents of second file are concatenated in it.
Is there any way to do that?
you can append another string in file by opening it in appending mode.
FILE *fp;
fp=fopen("file.txt","a");
here the next string will append after the last pointer of file.For more info link.
Yes, you can open the file with:
fopen("fileName", "a");
This will let you append to the end if the file.
More info is here: http://www.cplusplus.com/reference/cstdio/fopen/
It would help to know how you are trying to write the file. Likely, you are looking for the append option to FOPEN:
http://www.cplusplus.com/reference/cstdio/fopen/
FILE *f = fopen("foo.txt","a");
if (f != NULL) {
/* Use f */
fclose(f);
}

Resources