[英]How to open file in C program?
這里的代碼是來自網站的代碼。 由於我的原始代碼存在問題,我最終從一個網站嘗試了這個實現。 但事實證明我對這個程序也有同樣的問題
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("D:\\TestFile\\test.txt","r")) == NULL){
printf("Error! opening file\n");
perror(fptr);
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d\n", num);
printf("%s\n", fptr);
fclose(fptr);
return 0;
}
我被 if 條件所困擾,即,無論我做什么,我都無法讀取除根目錄之外的文件。 即使我指定了路徑,它仍然會在根目錄下查找文件。
我不確定為什么它不起作用,前提是相同的代碼在 Linux 中可以正常工作
我看到 2 個錯誤,一個與評論中提到的perror
相關,最后一個printf
。 現在,如果程序仍然無法運行,檢查錯誤或獲取程序 output 可能會很有趣。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("D:\\TestFile\\test.txt","r")) == NULL){
// printf("Error! opening file\n");
// perror(fptr); // MISTAKE-1: perror parameter is a string
perror("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d\n", num);
//printf("%s\n", fptr); // MISTAKE-2: fptr is not a string
fclose(fptr);
return 0;
}
發布的代碼沒有干凈地編譯!
以下是啟用了許多警告的編譯結果:
gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled1.c" -o "untitled1.o"
untitled1.c: In function ‘main’:
untitled1.c:11:16: warning: passing argument 1 of ‘perror’ from incompatible pointer type [-Wincompatible-pointer-types]
11 | perror(fptr);
| ^~~~
| |
| FILE * {aka struct _IO_FILE *}
In file included from untitled1.c:1:
/usr/include/stdio.h:775:33: note: expected ‘const char *’ but argument is of type ‘FILE *’ {aka ‘struct _IO_FILE *’}
775 | extern void perror (const char *__s);
| ~~~~~~~~~~~~^~~
untitled1.c:19:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘FILE *’ {aka ‘struct _IO_FILE *’} [-Wformat=]
19 | printf("%s\n", fptr);
| ~^ ~~~~
| | |
| | FILE * {aka struct _IO_FILE *}
| char *
Compilation finished successfully.
筆記; 聲明:編譯成功完成。 只是意味着編譯器對每個問題都應用了一些解決方法。 這並不意味着生成了正確的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.