【问题标题】:change from print to write file c从打印更改为写入文件 c
【发布时间】:2013-07-10 08:57:53
【问题描述】:

我有一个从xdr 文件读取输入并在 shell 上显示结果的代码,但我更喜欢程序以我可以使用 geany 或 nano 或其他方式读取的格式保存结果程式。 程序:

#include <stdio.h>
#include <stdlib.h>
#include <rpc/rpc.h> /* xdr is a sub-library of rpc */

#pragma comment(lib, "Ws2_32.lib") // Library for ntohl and htonl

main()
{
    // Reopens stdin to be the same input stream but in binary mode

     XDR xdrs;
    long i, j;

    FILE* fp;
    fp = fopen( "file.txt", "rb+" );

    xdrstdio_create(&xdrs, fp, XDR_DECODE);
    for (j = 0; j < 100; j++)
    {
        if (!xdr_long(&xdrs, &i)) {
            fprintf(stderr, "failed!\n");
            exit(1);
        }
        printf("%ld ", i);
    }

    printf("\n");
    exit(0);
}

如您所见,该文件会打印结果,但我更喜欢将其保存在我可以正常操作和读取的文件中。

非常感谢您的帮助。

【问题讨论】:

    标签: c printf fopen fclose xdr


    【解决方案1】:

    您可以这样做,也可以使用 dup2() 将输出重定向到文件

    #include <stdio.h>
    #include <stdlib.h>
    #include <rpc/rpc.h> /* xdr is a sub-library of rpc */
    
    #pragma comment(lib, "Ws2_32.lib") // Library for ntohl and htonl
    
    main()
    

    {

     // Reopens stdin to be the same input stream but in binary mode
    
     XDR xdrs;
    long i, j;
    
    FILE* fp,*fpwrite;
    fp = fopen( "file.txt", "rb+" );
    fpwrite = fopen("Myfile","w+");
    if(fpwrite == NULL){
         printf("Failed to open destination file\n");
    } 
    
    xdrstdio_create(&xdrs, fp, XDR_DECODE);
    for (j = 0; j < 100; j++)
    {
        if (!xdr_long(&xdrs, &i)) {
            fprintf(stderr, "failed!\n");
            exit(1);
        }
        printf("%ld ", i);
        fprintf(fpwrite,"%ld ",i);
    
    }
    
    printf("\n");
    fclose(fp);
    fclose(fpwrite);
    exit(0);
    

    }

    【讨论】:

    • 当我尝试这个时,我收到以下错误消息:decoder.c: In function ‘main’: decoder.c:14:9: error: incompatible types when assigning to type ‘FILE’ from type ‘struct FILE *’ decoder.c:15:12: error: invalid operands to binary == (have ‘FILE’ and ‘void *’) decoder.c:27:5: error: incompatible type for argument 1 of ‘fprintf’ /usr/include/stdio.h:357:12: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘FILE’ decoder.c:33:1: error: incompatible type for argument 1 of ‘fclose’ /usr/include/stdio.h:238:12: note: expected ‘struct FILE *’ but argument is of type ‘FILE’
    • 我解决了@Chinna 的问题,我必须在一行中声明一个文件并且:我不能在同一行中声明很多文件:FILE* a1,a2,...an; 我必须声明类似:FILE* a1; FILE* a2; ...
    • @PanichiPattumerosPapaCastoro 对不起,我看过了。但是你可以像这样声明文件 *fp,*fpwrite
    • 再次感谢您的帮助,另一个问题,如果我想为 esxample 的输出设置特定格式,我想要一个包含 n 列的矩阵,如何在代码中指定它?
    猜你喜欢
    • 1970-01-01
    • 2017-11-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多