謝謝,這已解決,請參閱答案中的更新代碼和輸出。感謝喬納森和其他人。儘管從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
它不應該是charÇ;? – MayurK
你有什麼文件?從哪裏打印成功?爲什麼你打印成功的錯誤? – khuderm
請發佈真實的代碼!你清楚顯示的內容不會編譯。 '文件名'應該用雙引號,但是如果你弄錯了,你顯然沒有複製'n'粘貼,所以我們不能相信代碼中的東西。請注意,即使它處理'成功'的情況,你的'else'子句也會輸出'ERROR'。 –