【发布时间】:2017-07-26 01:31:50
【问题描述】:
我正在编写一个程序,该程序从两个文件中获取字符串并将它们组合成带有组合字符串的第三个文件。
#define BUF 255
int main( void)
{
FILE *usernames; FILE *passwords; FILE *final_file;
char *user_str, *pass_str;
int ct, ck;
usernames = fopen( ".\\info_files\\usernames.txt", "r" );
passwords = fopen( ".\\info_files\\passwords.txt", "r" );
final_file = fopen( ".\\info_files\\usernamesPasswords.txt", "w" );
if ( (usernames == NULL) || (passwords == NULL) || (final_file == NULL)
)
{
printf( "failed to open one of the files" );
}
while ( (fgets( user_str, BUF, usernames) != EOF ) && ( fgets( pass_str, BUF, passwords) != EOF))
{
fprintf( final_file, "%-25s %s\n", user_str, pass_str );
}
fclose( usernames );
fclose( passwords );
fclose( final_file );
return 0;
}
这就是给我带来麻烦的原因。我不知道是什么导致它崩溃。 这是根据第一次发布的内容进行编辑的。
【问题讨论】:
-
while(fgets(user_str, BUF, usernames) && fgets(pass_str, BUF, passwords)){ fprintf( final_file, "%-25s %s\n", user_str, pass_str ); } -
可能你想从
user_str中删除换行符 -
!= EOF-->!= NULL,char *user_str, *pass_str;-->char user_str[BUF], pass_str[BUF]; -
读取fgets的引用返回值
-
user_str未分配也未初始化 -->fgets( user_str, BUF, usernames)--> UB。