从打印更改为写入文件 c

标签 c printf fopen fclose xdr

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

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

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

非常感谢您的帮助。

最佳答案

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

}

关于从打印更改为写入文件 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17566381/

相关文章:

C 将链表写入文件

c - 在 printf 中使用 (+ve integer) + "some string "?

php - 在集群文件上使用 file_get_contents 是否安全?

C无法打开文本文件

从 C 中的另一个文件创建一个新文件

c++ - GCC 和 Clang 是否优化逐字段结构复制?

c - 我只想在我的 C 程序中使用 iptables 命令

java - java中使用printf显示两位小数?

c - printf ("%s")、printf(s) 和 fputs 之间有什么区别?

c++ - 创建 C++ 共享库时,是否只需要附加库所依赖的 header ?