我無法將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 –