gpt4 book ai didi

从打印更改为写入文件 c

转载 作者:行者123 更新时间:2023-11-30 17:49:55 25 4
gpt4 key购买 nike

我有一个代码可以从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com