非便携式指针转换

时间:2017-07-26 01:31:50

标签: c file loops

我正在编写一个程序,它从两个文件中获取字符串并将它们组合在一起,形成带有组合字符串的第三个文件。

#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;
}

这就是给我带来麻烦的。我不知道造成这种情况的原因是什么。 这是根据首次发布的内容进行编辑的。

1 个答案:

答案 0 :(得分:1)

@BLUEPIXY为您提供了正确的代码 - 以下是您在代码中出错的原因: -

  

char * fgets(char * str,int n,FILE * stream)

     

从指定的流中读取一行并将其存储到str指向的字符串中。当读取(n-1)个字符,读取换行符或达到文件结尾时(以先到者为准),它会停止。

     

重新调整fgets的值

     

成功时:该函数返回相同的str参数

     

如果遇到文件结尾且未读取任何字符,   str的内容保持不变,返回空指针

     

如果发生错误,则返回空指针。

来源: - C Tutorial Point

相关问题