I have this code work :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *File_fp = fopen("Example.dat", "w");
char Temporary[50];
if(!File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
fprintf(File_fp, "This is an example.\n");
fgets(Temporary, 49, File_fp);
printf("It was \"%s\"\n", Temporary);
return EXIT_SUCCESS;
}
I printed "This is an example." in the file, "Example.dat" and I want to read it again from the file by code above but there's no string in the output. Why? Please help me.
You are opening the file in write-only mode ("w"). Use "w+" for reading and writing.
FILE *File_fp = fopen("Example.dat", "w+");
To read a file, you have to use the mode "r". Example:
FILE *File_fp = fopen("Example.dat", "r");
And you made a mistake in this code. If it fails to create a file, fopen() function will return NULL. Then the value of the file pointer would be NULL.
So, in your code if section will execute when the file is successfully created. So, change your code like this:
if(File_fp)
{
printf("An error occurred while creating the file.\n");
exit(1);
}
Just remove the (!) logical not sign.
Related
I was reading "C: How to program" on chapter 11 (File handling) and came with this algorithm, to append a string to a file named info.txt but it isn't working at all. What am I doing wrong?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
FILE *fp = fopen("info.txt","w");
char buff[100];
if(fp == NULL){
fprintf(stdout,"Error opening file\n");
exit(1);
}
while(!feof(stdin)){
fprintf(stdout,"Type a string/\nEOF ends input\n");
if(!fgets(buff,sizeof buff,stdin)){
fprintf(stderr,"Error reading string");
exit(2);
}
buff[strcspn(buff,"\n")] = 0;
fprintf(fp,"%s",buff);
}
fclose(fp);
}
I guess you are inserting EOF wrongly. As it is answered here, EOF is inserted using CTRL+D in Unix systems and using CTRL+Z in Windows.
Using exactly your code it works for me, so I guess you are trying to insert EOF using CTRL+C, or another command, which closes the application and leaves the file empty.
Also, if you want it to append always, even if you close the program and open it again, you should use the mode append "a" instead of write "w" [reference]
FILE *fp = fopen("info.txt","a");
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
Output is Error! opening file
I have program and txt file in same dir.
How can I direct access to that file?
To diagnose, use the system command to issue a ls or dir depending on your platform. That will tell you where you are running from. Odds are it is a different location than the files you are trying to open.
As suggested in the comment, try replacing printf with perror
if ((fptr = fopen("program.txt", "r")) == NULL)
{
perror("Error");
// Program exits if file pointer returns NULL.
exit(1); // Exiting with a non-zero status.
}
perror prototype is
void perror(const char *str)
where str is the C string containing a custom message to be printed before the error message itself.
However some causes of the of the file not being read are
File is not present in the current working directory. If this is the case, rectifying the path should fix the issue.
The program might not have the permissions to read from the file usually because of a setting related to discretionary access control. Perhaps do a chmod with file?
I made a quick run of your program on TURBOC++ by Borland and it executed without complaining any sort of Warning or Error
As mentioned in the earlier posted answers, you should replace printf by perror
CURRENT REPLACE BY
printf("Error! opening file"); perror("Error! Opening File.");
As in your case of file not found printf("Error! opening file"); will result in :
Error! Opening file.
However in case of perror("Error! Opening File."); if the file program.txt does not exist, something similar to this may be expected as program output
The following error occurred: No such file or directory
The difference is obvious from above explanations.
Regarding your program, I am making an assumption that either your path to the file is wrong or there is some problem with your compiler.
Try to open your file in w+ mode also to ensure that the file exist.
I am new to C, I am just trying to read a simple text file I created in C. I made this file by clicking new -> empty file -> saving it to my desired location and then adding the file extension (.txt) the text file holds a sample sudoku board and the full file name is sudokuchar.txt.
The code I have to read from the file and print it is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpointer = fopen("sudokuchar.txt", "r");
char input[100];
while(fgets(input,100,fpointer))
{
printf("%s",input);
}
fclose(fpointer);
}
so when i compile the program does not print anything and returns -1. I assume something is wrong with the file i am trying to read from?? if some one could help it would be greatly appreciated.
Always check the return values of fopen and other standard library calls. It's most likely that your file doesn't exist. You can make a nice user friendly error message using errno, just make sure to include errno.h. Overall, your code should work, but you NEED to check the return values of things, because fopen returns NULL if it can't find the file.
FILE *fpointer = fopen("sudokuchar.txt", "r");
if(fpointer == NULL) {
fprintf(stderr, "Error: [Errno %d]: %s\n",
errno, strerror(errno));
return 1;
}
It is advisable to check what file pointer returns. If file pointer returns 0 or NULL then File pointer is unable to point to the file name you had provided. Also you can use this
File *fp = fopen(file name with full path (i.e. /home/chex/read.txt),"r")
Check man fopen
FILE *fopen(const char *path, const char *mode);
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
printf("Writing to the file was successful.\n");
printf("Closing the program");
return 0;
}
I have tried this code to create a file in c programming and write the text "Hello world!" in it. What's wrong with this code?
If you want to know what is wrong check the result of fopen
opening = fopen("hello.usr","w");
if (opening == NULL) {
perror("fopen");
}
As of now, you don't know whether you managed to write to the file or not, so here's a suggestion which checks for it.
FILE *opening;
opening = fopen("hello.usr", "w");
if (opening == NULL){
perror("fopen");
return 0;
}
By returning 0 here you remove the option for segmentation fault as the code will still try to write to the file even if it doesn't exist.
The error message you are getting most certainly is NOT produced by a compiler. It looks to me as a message of some automatic checker that tests correctness of the submited solutions.
Make sure that the output matches exactly the required one.
The message:
Your program's output is shorter than the expected
may indicate that there is something wrong with new line characters ('\n'). Check for those.
For example if the required output is:
Writing to the file was successful. Closing the program.
... printed in one line, your output obviously doesn't match as it has a new line after the first sentence. And if the checker testes for the first occurrence of a new line character it sees only
Writing to the file was successful.
which could be one of many possible explanations. If this is the case try simply:
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
// printf("Writing to the file was successful.\n");
// printf("Closing the program");
printf("Writing to the file was successful. Closing the program\n");
return 0;
}
Note also that this sort of error messages (in automatic testing environments) are usually triggered by ommited, added extra or confused non-printable characters (spaces, tabs, new lines) or punctuation marks which is hard to notice.
You may also want to check in this respect the text you print to the file.
Try to Instead "w" use "wt" in fopen
Try the following
#include <stdio.h>
int main() {
FILE *opening = fopen("hello.usr", "w");
if(opening == NULL){
printf("An error occurred when opening the file!");
return 0;
}
else{
fprintf(opening, "Hello world!\n");
fclose(opening);
printf("Writing to the file was successful.\nClosing the program.\n");
}
return 0;
}
I am working through the excellent The C Programming Language at the moment, and have got stuck while trying to open and read a file. The program compiles, but seg faults on execution:
$ ./a.out
Segmentation fault
Here is the code:
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
fprintf(fp, "Testing...\n");
fclose(fp);
}
Note that the path points to a real file containing the string "hello, world".
Any ideas on where I am going wrong?
Make sure fp is not NULL before trying to write to it. For example:
if(fp == NULL)
{
fprintf(stderr, "Cannot open file\n");
return EXIT_FAILURE; // defined in stdlib.h
}
You need to open the file with something other than "r", which only allows file reading. Read the man page for fopen to find out which mode would work the best for you. Example:
"w" - Truncate to zero length or create file for writing.
"a" - Append; open or create file for writing at end-of-file.
You opened the file for reading only, and are attempting to write to it.
Use "a" if you want to append to the end of the existing file.
Edit: As others have noted, you're also not checking to see if the file was opened. fopen will return NULL if it fails and set the global variable errno to a value that indicates why it failed. You can get a human-readable explanation using strerror(errno)
if( fp == NULL ) {
printf( "Error opening file: %s\n", strerror( errno ) );
}
You are opening it in readonly mode! Need to use w or a for writing/appending to the file :)
fopen("/home/c-sandbox/index.html", "w");
You should check that fopen does not return NULL. I suspect it is returning NULL and either the fprintf and/or fclose calls are getting messed up.
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fgets(line,len,fp);
printf("%s",line);
fclose(fp);
fp=fopen("/home/c-sandbox/index.html", "a");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fprintf(fp, "Testing...\n");
fclose(fp)
}
for reading "hello, world" string present in file.
after reading write to the same file "Testing..."