我正在尝试使用 freopen 将标准输出打印到文件,并且下面的代码崩溃。我正在检查 NULL,并且我很确定我在程序的其他地方没有分段错误,因为我验证了我所有的 malloc 都是正确的。
程序在到达时崩溃fclose(stdout)
并且不打印我附加的错误消息以检查它。该printf("\nTestBeforeClose");
行打印但printf("\nTestAfterClose");
不打印。
int printAllVarRedir(char * filename, int redirmarker) {
var *current = NULL;
if (redirmarker == 1) {
if (freopen(filename, "w", stdout) == NULL) {
perror("Unable to open file");
return 1;
} else {
if (head == NULL) {
perror("No Variables");
fclose(stdout);
return 1;
} else {
current = head;
printf("%s=%s. Address is %p.Next is:%p\n", current->varname, current->value, current, current->next);
while (current->next != NULL) {
current = current->next;
printf("%s=%s. Address is %p.Next is:%p\n", current->varname, current->value, current,
current->next);
}
printf("\nTestBeforeClose");
if (fclose(stdout) == EOF) {
printf("\nError is %s\n", strerror(errno));
}
printf("\nTestAfterClose\n");
return 0;
}
}
}
}
这是我正在使用的 var 结构:
typedef struct varlist{
char * varname;
char * value;
struct varlist * next;
}var;
var * head = NULL;