I am new to writing c under linux so this will be maybe silly question, but I have problem using fopen. When I encountered the problem I just tried it with this really simple code:
#include <stdio.h> #include<stdlib.h> int main() { FILE *test; if( fopen("test.txt","r") == NULL ) printf("didnt open"); else printf("opened!"); fclose(test); }
test.txt is in same folder as this code and a.out. When I debug a.out I get:
Breakpoint 1, main () at testit.c:14 14 if( fopen("test.txt","r") == NULL ) (gdb) s _IO_new_fopen (filename=0x400696 "test.txt", mode=0x400694 "r") at iofopen.c:103 103 iofopen.c: No such file or directory. (gdb) s __fopen_internal (filename=0x400696 "test.txt", mode=0x400694 "r", is32=1) at iofopen.c:65 65 in iofopen.c (gdb) c Continuing. Program received signal SIGSEGV, Segmentation fault. _IO_new_fclose (fp=0x0) at iofclose.c:54 54 iofclose.c: No such file or directory.
I tried changing the path: if( fopen("/home/h1657/Work/test/test.txt","r") == NULL )
. Had the same effect.
I am sorry if this is basic question but I can’t find any solution to this.
Advertisement
Answer
Many issues in posted code:
You haven’t assign/initialize the file pointer
FILE *test;
. So it will point to nothing/garbage value. Now closing that usingfclose
cause undefined behaviour.may be crash your program.So the code should be
FILE *test; test = fopen("test.txt","r"); //close file pointer(after process on file) if fopen success.
confirm first what is your file name.if it’s
testtest.txt
OR
test.txt
ORtest.txt.txt
(in windows it will occur if you manually give.txt
extension and hide the extension ). Need to confirm it
first then according it give name in code.You have
int main
.So you should havereturn 0
at the end of the
main.