简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM