我尝试从另一个文件 file_in1 一次写入文本文件 fileout 一行,该文件是全局定义的。我从下面的代码中得到错误,我不知道为什么,如果有人能弄清楚为什么那么好。谢谢!
void output()
{
FILE *fileout;
char line[40];
file_in1 = fopen(filename1, "r");
printf("Please enter the name of the output file: ");
scanf("%s", filename); //Reads filename
fileout = fopen(filename, "w");
if (fileout == NULL) {
printf("(Ensure the file is located in the project \n file folder and has the .txt extension) \n");
output();
}
while (fgets(line, 90, file_in1) != NULL) //Looks through characters until end of the file
{
fputs(line, fileout);
}
}
答案 0 :(得分:4)
你宣布
char line[40];
但稍后再做
// v--- 90?
while (fgets(line, 90, file_in1) != NULL)
行不能容纳90个字符。要么line
更大,要么阅读更少的字符。
答案 1 :(得分:0)
以下代码
-
void output()
{
FILE *fileout;
char line[40];
//file_in1 = fopen(filename1, "r"); // <-- always check results
if( NULL == (file_in1 = fopen(filename1, "r") ) )
{ // fopen failed
perror( "fopen failed for input file" ); // writes failure details to stderr
exit( EXIT_FAILURE );
}
// implied else, fopen successful for input file
printf("Please enter the name of the output file: ");
//scanf("%s", filename); //Reads filename // <-- always check return code
// and allow for leaidng white space skipping
if( 1 != scanf( " %s", filename) )
{ // scanf failed
perror( "scanf failed for output file name" ); // writes failure details to stderr
}
// implied else, scanf for output file name successful
//fileout = fopen(filename, "w");
//if (fileout == NULL) // <-- always place the literal on the left to enable compiler to catch certain syntax errors
if( NULL == (fileout = fopen(filename, "w")))
{ // then, fopen failed
perror( "fopen failed for output file" ); // writes failure details to stderr
printf("(Ensure the file is located in the project \n file folder and has the .txt extension) \n");
// output(); <-- the program failed, do not continue and certainly not recursively
exit( EXIT_FAILURE );
}
// implied else, fopen successful for output file
//while (fgets(line, 90, file_in1) != NULL) //Looks through characters until end of the file
// <-- line is only defined as 40 characters
while( NULL != fgets(line, sizeof(line), file_in1))
{
fputs(line, fileout);
}
} // end function: output