c - Segmentation faults while opening file -


i'm getting confused right now. want create file , write string created before. when following code gets executed there happens segmentation fault error , program terminates.

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

the line declared following.

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

first i've considered error appears because of malloc, code isn't working either:

file* output; output = fopen("test.txt", "w"); fprintf(output, "lbasdhasd"); fclose(output); 

what doing wrong? in code runs before lines i've used file pointer file closed.

your code bad not check errors. output null pointer (and one):

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

are sure have permission create file in cwd?

fopen() sets errno error code in case of failure. usual strerror(errno) give description of error code.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -