我无法将FILE指针作为参数传递给多个函数。C:传递文件作为参数
我想打开main中的文件,然后将它传递给一个函数,它将写入一些东西,然后从该函数传递给另一个函数。我可以将它从主函数传递到第一个函数没有问题,但是当我尝试将它传递给第二个函数时,它会出现分段错误。
我的代码看起来是这样的:
void firstFunction(FILE*);
void secondFunction(FILE*);
int main(void) {
FILE *fp;
if((fp = fopen("test.txt", "ab+")) == 0) {
return 1;
}
firstFunction(fp);
return 0;
}
void firstFunction(FILE *fp) {
fprintf(fp, "test"); /* Works */
secondFunction(fp); /* Causes Segmentation fault */
}
void secondFunction(FILE *fp) {
/* never reaches here */
fprintf(fp, "test2");
}
这很好解释了我在哪里与此有关。我试过传递各种不同的语法,如secondFunction(* fp),但没有成功。
怎么回事?从主要功能到第一功能而不是从第一功能到第二功能时它是如何工作的?
编辑:实际代码
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LINESIZE 512
void runCommand(const char[], FILE*);
void append(const char[], FILE*);
int main(int argc, char * argv[]) {
char filename[LINESIZE];
FILE *fp;
char line[LINESIZE];
sscanf(argv[1], "%s", filename);
/* Open file for saving data */
if((fp = fopen(filename, "ab+")) == 0) {
perror("fopen");
return 1;
} else {
/* Reads lines from user */
while(fgets(line, LINESIZE, stdin)){
/* Omits empty lines */
if(strlen(line) > 1) {
runCommand(line, fp);
}
}
}
return 0;
}
/* Parses first word in input and executes proper command */
void runCommand(const char input[], FILE *fp) {
char param1[LINESIZE];
fprintf(fp, "test");
append(input, fp);
int r = sscanf(input, "%s", param1);
if (!strcmp(param1, "append")){
append(input, fp);
} else {
/* Error Handling */
}
}
void append(const char input[], FILE *fp) {
char command[7];
char fName[20];
char lName[20];
int score;
int r = sscanf(input, "%s%s%s%d", command, fName, lName, score);
if (r != 4) {
/* Error Handling */
}
fprintf(fp, "%s%s%d", fName, lName, score);
}
这是您的实际代码?它不会在第5行的'FILE * fp'和'#include'之后没有分号来编译。但随着这些改动,它在我的系统上编译和运行得很好。 –
请提供可以重现seg故障的真实代码。上面的代码不会有这样的结果。 – kaylum
http://stackoverflow.com/help/mcve –