簡體   English   中英

將終端輸出到C程序中的文件

[英]Piping terminal output to file from within C program

我希望將輸出到stdout的所有內容也保存在C代碼的文件中。 我知道我可以通過在命令行上調用該過程並將其通過管道傳輸到文件來做到這一點:

 myprogram.exe 1>logfile.txt

例如。 但是我想知道是否有一種方法可以從C代碼本身內部做到這一點。 printf()系列中是否有一個函數可以輸出到終端和具有相同參數的指定文件?

如果不是,編寫自己的printf()樣式的函數(使用與printf()相同的參數樣式)在其中調用printf()和fprintf()的語法將是什么?

您可以使用fprintf()函數,該函數在工作方式上與printf()非常相似。

這是一個例子:

FILE *fp;
int var = 5;
fp = fopen("file_name.txt", "w");// "w" means that we are going to write on this file
fprintf(fp, "Writting to the file. This is an int variable: %d", var);

您文件的輸出將是這樣的:

This is being written in the file. This is an int variable: 5

注意:每次使用w作為參數打開文件都會破壞文件的內容。

要寫入文件,必須使用文件操作命令,無法使用printf寫入文件(它僅打印到stdout)。 您可以使用:

sprintf(buf,"%d",var);  //for storing in the buffer
printf(buf);       //output to stdout
fputs(buf, fp);   //output to file

放棄使用可變參數函數的建議:

#include <stdio.h>
#include <stdarg.h>

/*
 * Not all compilers provide va_copy(), but __va_copy() is a
 * relatively common pre-C99 extension.
 */
#ifndef va_copy
#ifdef __va_copy
#define va_copy(dst, src) __va_copy((dst), (src))
#endif
#endif

#ifdef va_copy
#define HAVE_VACOPY 1
#endif

int
ftee(FILE *outfile, const char *format, ...)
{
    int result;
    va_list ap;
#if HAVE_VACOPY
    va_list ap_copy;
#endif

    va_start(ap, format);

#if HAVE_VACOPY
    va_copy(ap_copy, ap);
    result = vfprintf(outfile, format, ap_copy);
    va_end(ap_copy);
    if (result >= 0)
        result = vprintf(format, ap);
#else
    result = vfprintf(outfile, format, ap);
    if (result >= 0) {
        va_end(ap);
        va_start(ap, outfile);
        result = vprintf(format, ap);
    }
#endif
    va_end(ap);
    return result;
}

可以像標准fprintf函數一樣使用它,因為您可以指定輸出文件,除了它還會將常規輸出寫入stdout 我試圖支持相對較新的編譯器,這些編譯器仍然沒有va_copy()宏(在C99中定義),例如Visual Studio 2012附帶的宏(VS2013最終有了一個)。 一些C運行時還會有條件地定義va_copy() ,以便在啟用嚴格的C89 / C90模式的情況下進行編譯將使其未定義,而__va_copy()可能仍保持定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM