0

我有一个从文件读取输入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);
}

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

非常感谢你的帮助。

4

1 回答 1

0

您可以这样做,也可以使用 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);

}

于 2013-07-10T09:13:25.343 回答