【发布时间】:2015-04-24 08:41:43
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv)
{
int good_file = 0; //flag
FILE* files[argc - 1];
int i;
for(i = 0; i < argc - 1; i++){
if ((files[i]=fopen(argv[i+1], "r"))==NULL)
{
continue;
}
else //if file is good
{
good_file++; //increment then pass the ptr
test(files[i]); //of file to test function
}
}
if(!good_file){ //if flag good_file is 0 error
printf("ERROR!");
}
exit(0); //then exit program
}
int test (int *file) //takes in ptr to file[i] as param
{
char c;
while ((c = fgetc(file)) != EOF)
putc(c, stdout);
fclose(file);
return main //return main and continue loop
}
我知道我的代码是一团糟,但我试图接收 X 数量的文件,然后让程序测试以确保文件不为空或不存在,然后打印出它具有不同的功能。我正在尝试找到一种方法来成功地将指向文件的指针作为参数传递,这样它的内容就可以在不同的函数中打印到标准输出。完成后,让该函数将控制权返回给主函数,以便循环继续其进程。
【问题讨论】:
-
首先:正确缩进你的代码!。如果文件无法打开,您应该怎么做?如果您的规范是全部或全部,那么您就在正确的轨道上:打开所有文件,如果成功,则进行 seconf 循环以将所有文件内容复制到
stdout。如果文件无法打开,fprintf将错误消息发送到stderr而不是stdout,因此即使您将输出重定向到文件也是可见的。在复制循环中,使用int c;而不是char c;,这样您就可以将EOF与所有有效的char值区分开来。在test()中使用FILE *而不是int *。 -
如果你知道你的程序一团糟,最好的办法是先清理它。
-
想想如果我不传递任何参数会发生什么。你必须检查
argc -
啊,是的,如果没有参数,我需要先进行测试。感谢您指出了这一点。我已经解决了这个问题并将 int file 更改为 FILE 文件。
-
chqrlie,感谢您的洞察力......它已经清理了很多,我会做出调整!
标签: c function pointers parameters