2016-11-29 61 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); 

}} 

,我是越來越以下的輸出:

./a.out

Segmentation fault (core dumped) 

而一個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

它不應該是charÇ;? – MayurK

+0

你有什麼文件?從哪裏打印成功?爲什麼你打印成功的錯誤? – khuderm

+3

請發佈真實的代碼!你清楚顯示的內容不會編譯。 '文件名'應該用雙引號,但是如果你弄錯了,你顯然沒有複製'n'粘貼,所以我們不能相信代碼中的東西。請注意,即使它處理'成功'的情況,你的'else'子句也會輸出'ERROR'。 –

回答

1

爲避免此警告,您需要t您的代碼中有#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上打印任何內容。

編輯:只是增加對喬納森的有益的評論忽略編譯器的警告:

"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)."