如何在C程序中打开文件?

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。现在,如果程序仍然无法运行,检查错误或获取程序输出可能会很有趣。

#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.

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