【问题标题】:fprintf and looping in cfprintf 和 c 中的循环
【发布时间】:2018-04-11 00:05:06
【问题描述】:

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

虽然,当我尝试将相同的报告打印到磁盘文件时,我似乎无法弄清楚如何保留“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);

}

【问题讨论】:

  • 你试过什么?例如,如果您意识到printf(format,...);fprintf(stdout, format, ...); 相同,您可以使文件句柄成为您的函数的参数,例如void process(FILE *outfile) {...}。顺便说一句,while(!feof()) is almost always wrong.
  • 嗨@KenY-N,我试过这个: void summary (void) { reportfile = fopen("c:\\class\\mod5\\examples\\eweinrot_ie.txt"," w"); fprintf(reportfile,"The...\n"); fprintf(reportfile,"550...\n"); fprintf(reportfile,"Palm...\n\n"); fprintf(reportfile,"输入金额净额\n"); fprintf(reportfile,"---- ------ ---\n"); fprintf(reportfile,"%s %15.2f %17.2f\n",type,absamount,runningsum); fprintf(reportfile,"\n该月的净总额为 $%1.2f\n已处理的交易数:%d\n", total, count); fclose(报告文件); }
  • 不要对货币值使用浮点数。并且避免float,除非你真的明白你需要它。请改用double
  • 您需要的部分功能是 void header(FILE *fp) { fprintf(fp, "The MoneyMaking Corporation\n"); … } 之类的函数,您可以在其中调用 header(stdout) 写入标准输出(终端),并调用 header(fp) 写入由标识的文件流FILE *fp,您可以在 main() 中打开和关闭它。你可以把它做成一个文件或任何你喜欢的东西。您需要在process()summary() 中进行类似的更改。这基本上只是对 Ken Y-N 在他的评论中告诉你的内容的重述。
  • 好吧,那么你需要努力阅读你的书!现在!你不明白什么?函数参数?如何在编辑器中将printf( 更改为fprintf(fp,?我在示例中的函数中包含了您需要的语法更改——看看我是如何重写header() 的签名和第一行的。您在其他功能中进行等效更改。您似乎知道如何使用fopen() 打开文件;您只需要捕获返回的文件流(FILE * 值),然后将其传递给您的函数。这真的是微不足道的。当然,你也需要修改函数声明。

标签: c loops printf


【解决方案1】:

使用 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 代码。

【讨论】:

  • 还有 header()summary() 函数——让它们各自打开文件会很糟糕——至少效率低下。
猜你喜欢
  • 2016-08-12
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多