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.
Related
I wrote a program that asks the user to enter the full pathname of a file. It will then attempt to open that file from the pathname string provided. I used the standard error checking that most books have recommended, which is to close the program if fopen() returns NULL (which it will do in the case that the file does not exist). When I run the program and enter some random characters when prompted (obviously not a valid filename) my program hangs with a runtime error because it's trying to open that file that doesn't exist.
What is the point of the standard error check (pfile == NULL) if your program has already crashed when it calls fopen()? See below code.
I'm using LabWindows CVI 2017 as my enfironment which uses the clang compiler. See image of run time error.
#include <stdio.h>
#include <string.h>
#define MAX 200
int main (void){
char buffer[MAX];
int len = 0;
FILE *pfile = NULL;
printf("please enter the full pathname of the file you wish to process.\n");
fgets(buffer, MAX, stdin);
len = strlen(buffer);
buffer[len - 1] = '\0';
pfile = fopen(buffer, "r");
if(pfile == NULL){
printf("not a valid filename, press any key to exit.");
getchar();
return -1;
}
int sum = 0;
int c = 0;
while((c = fgetc(pfile)) != EOF){
sum += sizeof(c);
}
printf("the size of your file is %d\n", sum);
getchar();
return 0;
}
You are doing the proper error handling. Your program is valid in that respect. However, your IDE does some extra error checking, which is the cause of the behavior you're seeing.
The usual rules for error checking in these sorts of situations are:
Do check for error returns. (You're doing that.)
Do print a useful error message. (You're doing that.)
Print error messages to stderr.
If the error involves a file, do include the filename in the error message.
If the error involves a function that sets errno, do print the "perror" text" ("No such file or directory", etc.).
If you're writing a tool that will be combined into larger scripts, do include the program's name in the error message.
If the error occurs due to an input file you're reading, do print the name of that file and the line number.
Adopting rules 1 through 6, an improved version of your error check would be
if(pfile == NULL) {
fprintf(stderr, "%s: can't open %s: %s\n", progname, buffer, strerror(errno));
return EXIT_FAILURE;
}
For this to work you'll need both of:
#include <string.h>
#include <errno.h>
If that's too much work, a simpler way is just to call
perror(buffer);
although this falls down somewhat on rules 2, 6, and 7.
It's my first exercise about Files and I have to write some code so that if I write a word in the console, it gets printed in the file. The program ends if I input the word "fine" (it's Italian for end). It seems like the file is opened and closed correctly, the program reads the inserted chars, but nonetheless, the file remains blank.
I tried opening the file in various modes, I tried printing how many chars were read, I even tried deleting the file (but it actually does't exit even if I added exit(1).
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
FILE * fp;
char s[64];
if ((fp = fopen("prova.txt", "r+")) == NULL) {
printf("Error.\n");
exit(1);
}
do {
scanf("%s", s);
if (strcmp("fine", s) != 0) {
fprintf(fp, "%s ", s);
}
} while (strcmp("fine", s) != 0);
fclose (fp);
return 0;
}
It should save all the words in a text file, but it remains blank.
Your program looks OK. Most likely, you are checking the wrong file.
An educated guess: you are using some IDE. If this is the case, the file is created, but is created somewhere else. To be sure, print the working directory (man getcwd) somewhere in the beginning of your program, and look for the file there.
you have to use "w" to open a new file with write priviledges
change
if ((fp = fopen("prova.txt", "r+")) == NULL) {
with
if ((fp = fopen("prova.txt", "w+")) == NULL) {
EDIT: Maybe i didn't explained myself, r+ will fail if the file doesn't exist, changing it works for me
I have written a code in c, for file handling. The file name has some German characters in it. This code is working perfectly on Windows. But it is not working in Linux. fopen is giving 'Could not open file' error.
I have checked the file path, the file exists there. Also, I have read write permission for that folder.
The code is as below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *fileName = "/users/common/haëlMünchen.txt";
FILE * pFile;
char errorMessage[256];
pFile = fopen (fileName,"r");
if (pFile != NULL)
{
fprintf (stdout,"fopen example",errorMessage);
fclose (pFile);
}
else
{
sprintf(errorMessage, "Could not open file %s", fileName);
fprintf(stdout, "%s\n", errorMessage);
}
return 1;
}
Any inputs on this?
On Linux you could replace your sprintf call with
snprintf (errorMessage, sizeof(errorMessage),
"Could not open file %s - %m", fileName);
(A general hint is to avoid sprintf because of possible buffer overflows and only use snprintf)
If you want to avoid the GLibc specific %m format specifier, and use more standard functions, code
snprintf (errorMessage, sizeof(errorMessage),
"Could not open file %s - %s",
fileName, strerror(errno));
and don't forget the #include <errno.h>, and read carefully the errno(3) man page.
BTW, you could avoid doing both snprintf and printf and simply code
fprintf (stderr, "Cannot open file %s - %s\n",
fileName, strerror(errno));
(error reporting usually go to stderr, as Jonathan reminded)
Then run your program again. Perhaps you have an issue with character encoding (either in the source file, or in the filesystem).
You could also use strace (and perhaps ltrace) on your program to understand the actual syscalls it is doing.
Trying to learn C. Want to read the first line of a text file, my code is:
#include <stdio.h>
int main()
{
FILE *in = fopen("test.txt", "rt");
// read the first line from the file
char buffer[100];
fgets(buffer, 20, in);
printf("first line of \"test.txt\": %s\n", buffer);
fclose(in);
return 0;
}
I'm doing this in xCode. I get a exc bad access error.
test.txt definitely exists. It has one line that says "this is a text file"
try this after fopen() call:
if(in == NULL){
printf("Can't read teste.txt because: %s.\n", strerror(errno));
return 1;
}
and add the headers:
#include <errno.h>
#include <string.h>
The code looks fine, so my guess is that the program is not run in the same working directory as the file. Try placing the file in, say, /tmp/test.txt and use absolute path in fopen.
You don't check if the FILE is NULL. It may not be opened for a several reasons.
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..."