Basic file IO in C - c

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..."

Related

Why cannot I read string by fgets in C programming language?

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.

What is the correct way of changing mode of fopen after checking if file exists?

In my programm, I want to check if a logfile already exists and then write some data into it. Therefore I first opened it with mode "a". If this returned NULL, I reopend it with "w", wrote the header and opened it with "a" again to append the data. But after some time I always got "Too many open files" as error - so obviously opening the same file to the same pointer still opens a new handle (I wasn't aware of that). But now I'm not entirely sure how to write that part of the code - do I always have to fclose and then fopen again?
FILE *target;
target= fopen (ComplPath, "a");
if (target == NULL)
{
//fclose(target); ?!?!
target= fopen (ComplPath, "w");
if (target != NULL)
{
fprintf(target, "Header-Text \n");
fprintf(target, "Data" \n);
fclose(target);
}
else
{
printf("Error at writeToLog: %s\n", strerror(errno));
}
}
else
{
fprintf(target, "data");
fclose(target);
}
See after the first if: Do I have to close the file before reopening it with "w"? It seems quite inefficient to close and reopen a file all the time. Or is there in general some better way to do this task?
You should just open the file once with the "a" mode, and use ftell() to know if that created a new file.
Contrary to what your question suggests, both "a" and "w" will create a new file if it doesn't exist. The difference is that "w" will truncate it to zero length if it already exists.
FILE *target;
target= fopen (ComplPath, "a");
if (!target) {
/* error out */
}
if (ftell(target) == 0) {
/* write the header */
}

canĀ“t open txt file

#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.

fprintf crashes my program when it meets a \n

I am trying to make a report in a .txt file, but when my fprintf meets a \n it crashes. This is my code concerning the opening of the file and crashing:
FILE *f;
f = fopen("estructuras.txt", "w");
fprintf(f, "");
printf("3"); //This is the last thing I see.
fprintf(f, "TEXT TO INPUT\n")
fclose(f);
The problem is you didn't check whether the file opened. If it failed, it will return NULL and that will do bad things to fprintf.
Your first fprintf(f, ""); is a no-op. Printing an empty string does nothing, so that "works" (though I doubt that's guaranteed). printf("3"); does to stdout and is unaffected by the failed fopen. fprintf(f, "TEXT TO INPUT\n") finally tries to print to NULL and pukes.
All system calls have to be checked. They all have different return values on error. fopen returns NULL and the error lies in errno. There's many ways to do fopen error handling, here's one that I like which gives the user information to debug the problem.
#include <string.h> // for strerror()
#include <errno.h> // for errno
#include <stdio.h>
#include <stdlib.h>
int main(){
// Put the filename in a variable so it can be used in the
// error message without needing to be copied.
char file[] = "estructuras.txt";
FILE *fp = fopen(file, "w");
if( fp == NULL ) {
// Display the filename, what you were doing with it, and why it wouldn't open.
fprintf(stderr, "Could not open '%s' for writing: %s\n", file, strerror(errno));
exit(-1);
}
}
strerror(errno) turns the numeric errno error code into a human readable string. There are quotes around the filename in case extra whitespace snuck in.
So you'll get an error like Could not open 'estructuras.txt': No such file or directory.

Why does "w" in fopen here not create a new file?

The program always ends up exiting. I seem to be running in to this problem frequently and I think I somehow previously fixed it but I'm not sure how. Why does it not create a file?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (void){
FILE *fp;
int c;
char file_w[100];
char string[100];
printf("Enter filename\n");
fgets(file_w, 100, stdin);
fp = fopen(file_w, "w");
if (fp == NULL){
printf("Can't open file\n");
exit(0);
}
printf("Enter a string");
fgets(string, 100, stdin);
for(c = 0; c <= sizeof(string); c++)
{
fprintf(fp, "%s\n", string);
}
printf("file written");
fclose(fp);
return 0;
}
Try to print the name of the file you have entered:
printf("%s\n", file_w);
just after the line you get file_w, just to be sure to enter what you want. I same cases the terminal could be wrongly configured.
Try to enter an absolute name path, if your computer is a Linux or Unix:
/tmp/newfile.txt
If your computer is Windows... Well try to see if C:\temp\ exist (or create it) and then enter:
C:\temp\newfile.txt
In any case, remember that you can specify an absolute path, and not only the file name. So double check if you have the rights (i.e. the permissions) to write into the directory where the file should be written.
In case you want check the error and have a better description of the problem try to use the following lines instead of your code, just under the fopen
if( fp == NULL ) {
// Error, as expected.
perror( "Error opening file" );
printf( "Error code opening file: %d\n", errno );
printf( "Error opening file: %s\n", strerror( errno ) );
exit(-1);
}
strerror it is a wonderful function just because return you a description of the problem instead of an error code.
I bet the problem is "invisible character after actual name from fgets()". I'll let you figure out exactly what that character is, where it comes from and how to fix it, as "struggling to solve a problem" is part of the learning process when it comes to programming. If it was easy, everyone could do it.
If the return value of fopen is NULL it means some error occurred. I suggest you look into the errno global to see what error has occurred to help you debug why it's not opening the file.
The w flag does the following:
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.
So it should create a file when none exists, or when it does exist, overwrite its content.
If it does not do that, you have another problem, but from the little information you've given, it's hard to tell what it is.
I tried as a name of file the following:
C:\\temp\\test_file.txt
or
fopen("C:\\temp\\employees.txt", "w");
and it works fine, without errors (I made it in Windows 10. GCC win32, Version: 6.3.0).
I think that you have to use an absolute path to create the file.
use gets() instead of fgets()...it will work
.
.
gets(file_w);
.
.

Resources