c - 如何在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 中工作正常
解决方案
发布的代码没有干净地编译!
以下是启用了许多警告的编译结果:
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.
笔记; 声明:编译成功完成。 只是意味着编译器对每个问题都应用了一些解决方法。这并不意味着生成了正确的代码。
推荐阅读
- javascript - 我们如何以角度向 DOM 元素(来自 ts 文件)注入属性指令
- javascript - 在 Vue.js 中使用 $state 的最佳方式是什么?
- python - Azure Durable 函数 python DurableOrchestrationContext get_input 返回 null
- java - 将数组打印到控制台时是否可以隐藏数组中的元素?
- python - 在python中使用plotly的地震jsondata的Scattergeo
- javascript - 在 Mongoose 分页时更新 Javascript 函数
- html - 可见性属性在 html 文件中不起作用
- java - 如何在 Android 中不是 Activity 类的其他类中使用 Firebase Analytics?
- javascript - 当源是来自 Django 的字典时,使用预取 + 远程的 Typeahead Bloodhound 自动完成
- python - 使用 tkinter 在屏幕上显示图像的问题