Reputation: 57
hey guys i have got this code: (im trying to read a string and put it inside the output file)
#include "structs.h"
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE* input = fopen("journal.txt", "r");
FILE* output = fopen("output.txt", "w");
char date[9];
if( ferror(input) || ferror(output) ) {
perror("Error opening input/output file\n");
}
fscanf(input, "%s", date);
fgets(date, 9, input);
fputs(date, output);
fclose(input);
fclose(output);
return 0;
}
it compiles properly but at runtime it shows the error
Segmentation fault (core dumped)
i have no idea why :( please help
Upvotes: 0
Views: 7477
Reputation: 182
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE* input = fopen("journal.txt", "r");
FILE* output = fopen("output.txt", "w");
char date[9];
if(input)
{
fscanf(input, "%s", date);
fgets(date, 9, input);
}
else
{
printf("error opening the file");
}
if(output)
{
fputs(date, output);
}
else
{
printf("error opening the file");
}
You were receiving the Segmentation fault as you were reading from a non-existing file 'journal.txt' and calling Ferror triggers Segmentation Fault.
Upvotes: 0
Reputation: 105935
You need to check whether fopen
returns NULL
:
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * input;
FILE * output;
char date[9];
input = fopen("journal.txt", "r");
if(input == NULL){
perror("Could not open input file");
return -1;
}
output = fopen("output.txt", "w");
if(output == NULL){
perror("Could not open output file");
fclose(input);
return -1;
}
/* ... snip ... */
Your input file probably doesn't exist. Calling ferror
on NULL
results in a segmentation fault.
Upvotes: 5