如何使用freopen重定向输出?

问题描述 投票:0回答:1

目前,这是我创建的代码,但我似乎无法找到它背后的问题。我正在写一个加密的程序

int countWords(FILE *f){
   int count = 0;
   char ch;
   while ((ch = fgetc(f)) != EOF){
       if (ch == '\n')
           count++;
   }
   return count;
}

int main ( int argc, char *argv[] ){
    //int min > 0; 
    //int max >= int min; 
    time_t current_time;
    char* c_time_string;

    current_time = time(NULL);

    /* Convert to local time format. */
    c_time_string = ctime(&current_time);

    printf("Program started %s\n", c_time_string);


    if ( argc != 2 ){ 
        printf( "usage: %s filename\n", argv[0] );
    }else {
        int wordCount = 0;
        FILE *file = fopen( argv[1], "r" );
        //wordCount += countWords(file);
        //printf("Total number words processed => %d\n", wordCount);

    if ( file == 0 ){
        printf( "Could not open file.\nProgram halted. Please verify the file path and try again.\n" );
    }else {
            int x;
            while  ( ( x = fgetc( file ) ) != EOF ){
                printf("%c", x );
            }
            fclose( file );
        }


                /// CRYPT ///

         char * plaintext = argv[1] ;
         char * hash_type_1 = "$1$";  // type 1 implies md5 (number of iteration is only 1000 rounds)
         char * hash_type_2 = "$6$";  // type 2 implies sha-512 (default value as in yr 2017, number of iteration is minimum 10,000 rounds )
         char * salt_1 ="$";           // a simplified 0 length salt.
         char * salt_2 ="ABCD1234$";   // a normal 8 character salt.
         char * result;
         char encyption_scheme[20]; // 20 is more than enough.

         // prepare the first call using md5 and empty salt

         strcpy(encyption_scheme,hash_type_1);
         strcat(encyption_scheme,salt_1);
         result = crypt(plaintext,encyption_scheme);
         printf("MD5: %s\n",result);
         // prepare the second call using sha-512 and a 8-char salt
         strcpy(encyption_scheme,hash_type_2);
         strcat(encyption_scheme,salt_2);
         result = crypt(plaintext,encyption_scheme);
         printf("Sha512: %s\n",result);
         printf("Program ended %s\n", c_time_string);

        //transfer the output to mytab2411.txt//
        result = freopen("mytab2411.txt", "w+", stdout);

    }
            return 0; 
}

我的编码需要一些帮助。我正在尝试编写一个能够将程序输出传输到空文件的程序。请帮我找到我的错误。

c
1个回答
0
投票

关于:

//transfer the output to mytab2411.txt//
result = freopen("mytab2411.txt", "w+", stdout);

对I / O的修改仅适用于调用后的输出。

建议将此语句放在代码的“加密”部分的开头。

© www.soinside.com 2019 - 2024. All rights reserved.