2013-07-10 166 views
0

我有一個代碼從xdr文件讀取輸入並在shell上顯示結果,但我更喜歡程序將結果保存爲我可以用geany或nano或其他人讀取的格式程式。 程序:從打印變爲寫入文件c

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

正如你所看到的文件打印的結果,但我更喜歡它保存它,我可以操作和正常讀取的文件。

非常感謝您的幫助。

回答

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

}

+0

當我嘗試這方面,我收到以下錯誤消息輸出重定向到文件:decode.c:'in'main': decoder.c:14:9:錯誤:從類型'struct FILE *'分配類型'FILE'時的不兼容類型 decoder.c:15:12 :error:無效的操作數爲二進制==(有'FILE'和'void *') decoder.c:27:5:error:'fprintf'參數1的不兼容類型 /usr/include/stdio.h: 357:12:note:expected'struct FILE * __restrict__'but argument is of'FILE' decoder.c:33:1:error:'fclose'參數1的不兼容類型 /usr/include/stdio.h :238:12:note:expected'struct FILE *'but argument is of'FILE'' –

+0

我解決了問題@Chinna,我必須在一行中聲明一個文件,並且:我不能在相同的行:'FILE * a1,a2,... an;'我必須聲明如下:'FILE * a1; FILE * a2; ...' –

+0

@PanichiPattumerosPapaCastoro對不起,我看着它。但你可以聲明像這樣的文件* fp,* fpwrite – Chinna