I'm getting really confused right now. I want to create a file and write to it a string which was created before. But when the following code gets executed there happens the segmentation fault error and the program terminates.

FILE* output; output = fopen("test.txt", "w"); fprintf(output, line); fclose(output); 

The line is declared as the following.

char* line = NULL; line = malloc(1048576 + 1); 

First I've considered that the error appears because of the malloc, but this code isn't working either:

FILE* output; output = fopen("test.txt", "w"); fprintf(output, "LBASDHASD"); fclose(output); 

What am I doing wrong? In the code which runs before that lines I've used a file pointer too but the file is already closed.

5

2 Answers

Your code is bad as you do not check for errors. output could be a NULL pointer (and is likely to be one):

#include <errno.h> #include <string.h> FILE* output; output = fopen("test.txt", "w"); if(!output){ //handle the error printf("something went wrong: %s", strerror(errno)); exit(1); } fprintf(output, "LBASDHASD"); fclose(output); 

Are you sure you have permission to create the file in the CWD?

fopen() sets errno to an error code in case of a failure. As usual strerror(errno) will give you a description of this error code.

0

See if you have the filename correctly or not and make sure it is in the same directory, otherwise provide the full path of the file. If it is mistaken then it will not open and make sure of the file permission.

#include <stdio.h> int main() { FILE *output; output = fopen("test.txt","w"); if(output==NULL) { printf("Error in opening the file"); return 0; } fprintf(output, "%s", "LBASDHASD"); fclose(output); return 0; } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy