繁体   English   中英

如何在 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 现在,如果程序仍然无法运行,检查错误或获取程序 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM