2016-11-29 4 views
-3

감사합니다.이 문제가 해결되었습니다. 업데이트 된 코드와 대답을 확인하십시오. 조나단과 다른 모든 사람들에게 감사드립니다.fopen()에서 성공을 얻었음에도 불구하고 C에서 파일을 읽을 수 없습니다

동일한 디렉토리에있는 파일을 읽으려면 아래 코드를 작성했습니다.

#include<stdlib.h> 
#include<stdio.h> 
#include<errno.h> 
int main(){ 

FILE *fptr; 


/*Tried putting different combinations like filename with  
quotes|filename without quotes|complete path with quotes|complete path 
without quotes*/ 

if((fptr=fopen("TestFile.txt","r"))==NULL){ 

printf("\nfopen() returning NULL: %d , %s \n",errno,strerror(errno)); 

}else{ 
printf("\nfopen() returning something else: %d , %s 
\n",errno,strerror(errno)); 
} 

int c; 

while((c=fgetc(fptr))!=EOF){ 

printf("%c",c); 

}} 

그리고 난 출력 아래 얻고 있었다 오전 :

Segmentation fault (core dumped) 

./a.out 그리고 GDB 코어 분석은 다음했다 :

(gdb) run 
Starting program: /home/astitva/Documents/Coding/a.out 
Dwarf Error: wrong version in compilation unit header (is 0, should be 2, 
3, or 4) [in module /usr/lib/debug/.build- 
id/12/5dab90a4cfa8edc5d532f583e08e810c232cd5.debug] 
warning: Could not load shared library symbols for linux-vdso.so.1. 
Do you need "set solib-search-path" or "set sysroot"? 
Dwarf Error: wrong version in compilation unit header (is 0, should be 2, 
3, or 4) [in module /usr/lib/debug/.build- 
id/c0/5201cc642f6b800835e811d7cb28f103aeb191.debug] 


Program received signal SIGSEGV, Segmentation fault. 
0x00007ffff7abc496 in strlen() from /lib/x86_64-linux-gnu/libc.so.6 


and my text file TestFile.txt was : 

DATA ENETERD AT RUN INSTANCE 1 ------> BLABLABLA 
DATA ENETERD AT RUN INSTANCE 2 ------> YADAYADAYADA 
DATA ENETERD AT RUN INSTANCE 3 ------> FOOBARFOOBAR 
+2

을;? – MayurK

+0

파일에 무엇이 있습니까? 그 성공은 어디에서 인쇄됩니까? 왜 성공에 대한 오류를 인쇄하고 있습니까? – khuderm

+3

실제 코드를 게시하십시오! 당신이 분명히 보여주는 것은 컴파일되지 않습니다. '파일 이름'은 큰 따옴표로 묶어야하지만 잘못 입력하면 코드를 복사 할 수 없으므로 코드에있는 내용을 신뢰할 수 없습니다. 'else' 절은 'success'를 처리 할지라도'ERROR'를 출력합니다. –

답변

1

경고를 피하려면 다음을 수행해야합니다. 코드에서 #include <string.h>. 오류 처리 if 블록에 exit(1) 추가 : 파일이 존재하지 않는 경우

if((fptr=fopen("TestFile.txt","r"))==NULL){ 
    printf("\nfopen() returning NULL: %d %s\n",errno, strerror(errno)); 
    exit(1); 
} 

이 프로그램은 "gracefully"을 종료해야합니다. 따라서 유효한 파일이 없으면 프로그램은 종료하고 stdout에 아무 것도 인쇄하지 않습니다.

편집 : 그냥 컴파일러의 경고를 무시에 조나단의 도움이 코멘트에 추가 : 그것은 문자 C 있어야하지

"If you ignored a compiler warning — don't. If the compiler didn't warn you about the undeclared function strerror(), you need to find the options that make it report such problems (if you use gcc, you would use gcc -Wall -Wextra -Werror — and I'd add -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Wold-style-declaration too, though clang doesn't like -Wold-style-declaration)."

관련 문제