fprintf() function in C is not working properly - c

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.

Related

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.

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

File Modes in Binary

Well I was looking into ways to open a file in binary and I saw that you can open one for r+b and a+b but whats the difference because this is what it says for definition.
a+b :Open a file for both reading and writing in binary mode.
r+b: Open a file for both reading and writing in binary mode.
a+b
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
r+b Open for reading and writing. The stream is positioned at the beginning of the file.
w+b 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.
So, a+b will create the file if it does not exist, and it will append to the file when you write to it,
r+b will not create the file if it doesn't already exist (fopen() would fail), and writing to the file will start at the beginning of the file.

Read and write in place not writing?

New to C and I'm trying to do a text replace in place. I thought r+ in fopen should allow me to read and write. I'm looking at every line in the file and if it begins with a / then I am prepending http://example.com to the beginning of the line. Example...line is /tree then that line becomes http://example.com/tree. The regex works fine. I can read the file fine but it is not writing. Any ideas why?
void
fix_relative (char *page)
{
FILE *fp;
fp = fopen ("file", "r+");
char line[1000];
regex_t re;
regcomp (&re, "^/", REG_EXTENDED);
while (fgets (line, sizeof line, fp) != NULL)
{
if (regexec (&re, line, 0, NULL, 0) == 0) {
fprintf (fp, "http://example.com%s\n", line);
}
}
fclose (fp);
}
No way this can possibly work. You will run into a problem as soon as your new string is not exactly as long as the original string. In addition, since you are working in text mode, there may be additional artefacts because of newline/carriage return translation.
Instead, do the following:
open the file "file" for reading only
create a new temporary file for writing only
read a line, modify if necessary, write to new file
when done, delete "file" and rename your temp file.
This may help you to understand your problem
fopen function
Purpose:
Opens a stream. The safer fopen_s function is also available.
Syntax:
FILE * fopen(const char *name, const char *mode);
Declared in:
The fopen function opens the file whose name is the string pointed to by name, and associates a stream with it. The string may contain a full path (from the root), a relative path (from the current directory) or just a name.
The argument mode points to a string. If the string is one of the following, the file is open in the indicated mode.
"r" Open text file for reading.
"w" Truncate to zero length or create text file for writing.
"a" Append; open or create text file for writing at end-of-file.
"rb" Open binary file for reading.
"wb" Truncate to zero length or create binary file for writing.
"ab" Append; open or create binary file for writing at end-of-file.
"r+" Open text file for update (reading and writing).
"w+" Truncate to zero length or create text file for update.
"a+" Append; open or create text file for update, writing at end-of-file.
"rb+" Open binary file for update (reading and writing).
"wb+" Truncate to zero length or create binary file for update.
"ab+" Append; open or create binary file for update, writing at end-of-file.
"r+b" Same as "rb+"
"w+b" Same as "wb+"
"a+b" Same as "ab+"
Opening a file with read mode ('r' as the first character in the mode argument) fails if the file does not exist or cannot be read.
Opening a file with append mode ('a' as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function.
When a file is opened with update mode ('+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.
When opened, a stream is fully buffered if and only of it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream are cleared.
Returns:
A pointer to the object controlling the stream on success, otherwise a null pointer.
One thing that may not be clear: if you update lines in the file, and your replacement text is not precisely the same length as what it is replacing, you will make a complete hash of the file: you will be overwriting what comes after it.
So, if you have a file that contains the sentences:
I love programming.
I love life.
and you set the file position to the first sentence and replace "love" with "loathe", you will NOT get
I loathe programming
I love life
You will get
I loathe programming love life
because you have now overwritten the line separator from the first sentence, and the "I" from the next sentence.
If you replace a string with a longer string, that will push every other character in the file forward. To do that replacement, you'd have to read the entire file into memory, do your replacements, and then write the file back out to disk.

is there any option to create an output text file in the name of the input file in c programm?

is there any option to generate an output text file as same as the input file name?
in C i got the file name using:
gets(file_name);
and open it through the:
f1=fopen(file_name,"r");
comment.how do i open the file without entering the format type?
for example for file100.txt i'd like to enter file100 to read the file.
and any option to get the output file as same name as the input file?
You can use
snprintf(new_filename, sizeof new_filename, "%s.%d", File_name, int_val);
For your problem with the file name, you can use e.g. sprintf:
char full_file_name[256];
sprintf(full_file_name, "%s.txt", file_name);
This is not recommended without some validation of the entered file name of course.
For your other problem, from the documentation of fopen:
r+ Open for reading and 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.
a+ Open for reading and appending (writing at end of file). The file is
created if it does not exist.
The initial file position for reading is at the beginning of the file,
but output is always appended to the end of the file.
for creating output file with the same name, simply save your output content into some string. Then, close the file and open it again with write mode("w"). And then, write the content and close the file again.

Resources