我有一个程序正在创建多个文件。创建的每个文件都有一个函数。在每个函数中都有完全相同的代码来创建文件名、打开/创建要写入的文件、设置其权限并在最后关闭文件。我决定创建一个函数来打开文件和关闭文件,这样我就可以调用它,而不是每次都使用相同的代码前面的代码在每个函数中如下所示:
void WriteFile1(char *name) {
FILE *file;
char *filename; //This is being malloc'ed because it initially consisted of multiple strings
if (!(filename = malloc(sizeof(char *) * (strlen(name) + 1)))) MallocError();
if (!(file = fopen(filename, "w"))) {
fprintf(stderr, "Unable to open %s. Exiting \n", filename);
exit(1);
}
fchmod(fileno(file), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH);
//a bunch of fprintf statements here
if (fclose(file)) {
fprintf(stderr, "Error closing %s. Exiting...\n", filename);
exit(1);
}
}
这很管用。我没有问题。现在看起来如下:
void WriteFile1() {
FILE *file;
OpenFile(file, "filename.asdf");
//fprintf statements
CloseFile(file, "filename.asdf");
}
void OpenFile(FILE *file, char *name) {
if (!(file = fopen(name, "w"))) {
fprintf(stderr, "Unable to open %s. Exiting... \n", name);
exit(1);
}
fchmod(fileno(file), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH);
}
void CloseFile(FILE *file, char *name) {
if (fclose(file)) {
fprintf(stderr, "Error closing %s. Exiting...\n", name);
exit(1);
}
}
当我到达WriteFile1()中的第一个fprintf语句时,它将隔离错误。我对文件变量做了什么不正确的事情吗?看起来它应该像以前一样工作。唯一的区别是文件名字符串的malloc,我将其作为名称传递,并用引号给出实际值。
谢谢你
最佳答案
这段代码是错误的:
void OpenFile(FILE *file, char *name) {
if (!(file = fopen(name, "w"))) {
在这里,您只需分配给局部
file
变量。必须返回
file
,这样WriteFile1()函数才能处理该文件*void WriteFile1() {
FILE *file;
file = OpenFile("filename.asdf");
//fprintf statements
CloseFile(file, "filename.asdf");
}
FILE * OpenFile(char *name) {
FILE * file;
if (!(file = fopen(name, "w"))) {
fprintf(stderr, "Unable to open %s. Exiting... \n", name);
exit(1);
}
fchmod(fileno(file), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH);
return file;
}
关于c - fopen/fclose上的段故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6332354/