尽管从fopen()获得成功,仍无法读取C中的文件

时间:2016-11-29 05:02:18

标签: 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

1 个答案:

答案 0 :(得分:1)

要避免此警告,您需要在代码中#include <string.h>。在错误处理exit(1)块中添加if

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

如果文件不存在,程序需要退出"gracefully"。因此,如果没有有效文件,程序将只退出并且不在stdout上打印任何内容。

编辑:只是添加Jonathan关于忽略编译器警告的有用评论:

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