[英]C, Passing a pointer of a file to a function
#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數量的文件,然后進行程序測試以確保文件不為空或不存在,然后將其內容打印到不同的功能。 我試圖找到一種方法來成功地將指針作為參數傳遞給文件,以便可以在其他函數中將其內容打印到stdout。 然后,完成該操作后,讓該函數將控制權返回給主函數,以使循環繼續其過程。
您的test
函數是bogous(在參數fgetc
使用int
代替FILE
,並使用char
代替int
。
嘗試這個:
void test (FILE *file) //takes in ptr to file[i] as param
{
int c;
while ((c = fgetc(file)) != EOF)
putc(c, stdout);
fclose(file);
}
雖然可能還有更多問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.