【发布时间】:2021-04-19 13:17:22
【问题描述】:
我正在尝试打印文件中包含的内容,但是当部分代码包含在如下函数中时它不起作用:
#include <stdio.h>
#include <stdlib.h>
main() {
FILE *file;
file = fopen(path, "rt"); //Instead of "path" there is the file's path
read(file);
fclose(file);
return 0;
}
void read(f) {
int c;
if (f)
while ((c = getc(f)) != EOF)
putchar(c);
}
但是,当我像这样在 main 中编写所有内容时,它确实有效:
#include <stdio.h>
#include <stdlib.h>
main() {
FILE *file;
file = fopen(path, "rt");
int c;
if (file)
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
return 0;
}
为什么它不起作用?任何帮助将不胜感激
【问题讨论】:
-
你的 C 编译器没有给出任何警告吗? clang 和 gcc 都会使用默认参数产生一些错误和警告。
-
函数
main()只有两个有效签名,它们是:int main( void )和int main( int argc, char * argv[] ) -
这里是函数的原型:
read():ssize_t read(int fd, void *buf, size_t count);read()是一个众所周知的 C 库函数,尝试用自己的代码替换 C 库函数是一种糟糕的编程习惯, 建议叫它MyRead() -
关于:
file = fopen(path, "rt");1) 变量:path未定义,2) 始终检查 (!=NULL) 返回值以确保操作成功,如果不成功 (== NULL) 然后调用perror( "fopen failed" )这样您的错误消息和系统认为发生故障的文本原因都输出到stderr -
关于:
void read(f) {编译器将假定参数的类型为int,这将不起作用,要更正此问题,请在 main() 之前放置一个原型,类似于:`void read(文件 f);