0

我正在尝试将标准输出更改为文件,写一些东西然后将其重新运行回屏幕。我的代码是:

FILE *stream ;
char * file_name = "LRA_SOLVER";
char * file_ext = ".txt";
char file_number [3] = {0};
itoa (lra_solver_couter++,file_number,10);
char* file_full_name = (char*)calloc(strlen(file_number)+10+4,sizeof(char));
strcpy(file_full_name, file_name);
strcat(file_full_name, file_number);
strcat(file_full_name, file_ext); 
if((stream = freopen(file_full_name, "w", stdout)) == NULL)
    exit(-1);
print(); // a lot of printing into the file.
stream = freopen("CON", "w", stdout); // change it back
free(file_full_name);

但我检测到错误堆损坏...... lra_solver_couter 不大(通常为0-20)。我究竟做错了什么 ?

4

1 回答 1

1

当您计算所需的长度时,您忘记了终止 '\0' file_full_name:您只有strlen(file_number)+10+4with10 == strlen(file_name)4 == strlen(file_ext)。添加1为“\0”。

于 2013-07-24T12:09:28.257 回答