c - fprintf 和循环在 c

标签 c loops printf

我成功编写了这个在终端输出报告的程序。

虽然,当我尝试将相同的报告打印到磁盘文件时,我似乎无法弄清楚如何保留“while”循环并将所有报告打印到磁盘文件。

我已经尝试了一些方法,比如删除“header”函数并将该语法与所有必要的“fprintf”语句一起放入“summary”函数中。其结果只是一行出现在磁盘文件输出中。这是 transactiondata.txt file :

IMPORT     -25.19
EXPORT      35.41
EXPORT     100.25
IMPORT    -500.34
EXPORT     240.35
IMPORT    -134.56
EXPORT     459.56

我应该如何构建代码,以便在磁盘文件中获得与终端窗口中显示的相同输出?

磁盘文件输出应该是look like this

The MoneyMaking Corporation
550 Warm Sands Drive
Palm Springs, CA 92262

Type            Amount              Net
----            ------              ---
IMPORT          -25.19            -25.19
EXPORT           35.41             10.22
EXPORT          100.25            110.47
IMPORT         -500.34           -389.97
EXPORT          240.35           -149.52
IMPORT         -134.56           -284.08
EXPORT          459.56            175.48

The net total for the month is $174.48
Transactions processed: 7

这是我的代码:

//C Libraries
#include <stdio.h>
#include <math.h>

//Global Variable Declarations

FILE *datafile;                  //disk file (for input)
FILE *reportfile;                // report file (for output)
char type [7];                   //Transaction Type: either IMPORT or EXPORt

float amount;                     //Transaction Amount
float absamount;                  //abs amount
float total;                      //Total
float runningsum;                 // End net balance at end of every transaction
int count;                        //Count of transactions

// Function Prototypes

void header (void);
void process (void);
void summary (void);

//*************************************************
//*************************************************
// M A I N   F U N C T I O N
//*************************************************
//*************************************************


int main (void){
// Initialize accumulating variables
    datafile = fopen("c:\\class\\mod5\\examples\\transactiondata.txt","r");   // Open input file
    count = 0;
    total = 0.00;
    runningsum = 0.00;

// Produce Report

   header();
   process();
   summary();

   fclose(datafile);
   system("pause");
   return 0;

}

// *************************************************************
// Header - prints a header on the report
// *************************************************************

void header (void)
{
    printf("The MoneyMaking Corporation\n");
    printf("550 Warm Sands Drive\n");
    printf("Palm Springs, CA 92262\n\n");

    printf("Type            Amount              Net\n");
    printf("----            ------              ---\n");
}

// *************************************************************
// Process - produces the detail lines of the report
// *************************************************************


void process (void)
{
    while(!feof(datafile))
    {
        fgets(type, 7, datafile);
        fscanf(datafile,"%f\n", &amount);
        absamount = fabs(amount);
        runningsum = amount + runningsum;
        printf("%s %15.2f %17.2f\n",type,absamount,runningsum);

    count++;              // You could also use count = count + 1
    total = total + amount;
    }


}

// *************************************************************
// Summary - prints the report summary (including accumulators)
// *************************************************************

void summary (void)
{
    // Local Variables

    float net;  //net values


    printf("\nThe net total for the month is $%1.2f\nTransactions processed: %d\n", total, count);

}

最佳答案


使用 fprintf。

void process (void)
{
    FILE *of = fopen("O_File", "a"); // reportfile the report file I guess
    while(!feof(datafile))
    {
        fgets(type, 7, datafile);
        fscanf(datafile,"%f\n", &amount);
        absamount = fabs(amount);
        runningsum = amount + runningsum;
        fprintf(of, "%s %15.2f %17.2f\n",type,absamount,runningsum);
        fprintf(stdout, "%s %15.2f %17.2f\n",type,absamount,runningsum); // to print to console

    count++;              // You could also use count = count + 1
    total = total + amount;
    }
    fclose(of);

}

至少可以说,我应该更加注意,我的上述逻辑几乎是具有多个开口的低效代码,如果将 fopen 和 fclose 调用移至 main() ,服务器会更好。并且考虑到 FILE *reportfile 是全局的,除了将 fprintf 调用更改为使用 reportfile 而不是 of 进行写入之外,不需要太多内容。

而不是使用那些 fprintf 调用打开重新打开关闭逻辑

这段代码

int ofd = open("O_File", O_RDWR|O_APPEND);
close(1);
close(2);
dup(ofd);
close(ofd);

在调用下面的代码序列之前

// Produce Report

   header();
   process();
   summary();

应该服务于目的,

man -a dup

P.S - 几乎所有 Linux 代码都没有在其他平台上测试过。

关于c - fprintf 和循环在 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007980/

相关文章:

c - malloc/calloc 分配的 block 的差异

c - 无论质量如何,都以最佳压缩方式用 C++ 录制音频

c++ - 递增预处理器宏

python - 确保同名文件始终匹配?

python - 如何使用Python迭代Mysql数据库查询?

c - printf 打印出错误的值

perl - 分块打印

c - 如何为简单的命令行解释器解析 fgets 中的字符串以存储在 argv[] 中?

cat/Xargs/command VS for/bash/command

winapi - Lua 字符串不会连接