首页 > 解决方案 > 如何在C程序中打开文件?

问题描述

这里的代码是来自网站的代码。由于我的原始代码存在问题,我最终从一个网站尝试了这个实现。但事实证明我对这个程序也有同样的问题

#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 中工作正常

标签: cfileio

解决方案


发布的代码没有干净地编译!

以下是启用了许多警告的编译结果:

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.

笔记; 声明:编译成功完成。 只是意味着编译器对每个问题都应用了一些解决方法。这并不意味着生成了正确的代码。


推荐阅读