2017-10-30 2 views
3

터미널에 보고서를 출력하는이 프로그램을 작성했습니다.fprintf 및 루핑 in c

동일한 보고서를 디스크 파일로 인쇄하려고하면 'while'루프를 보존하고 모든 보고서를 디스크 파일로 인쇄하는 방법을 알아낼 수 없습니다.

'헤더'기능을 제거하고 거기에 필요한 모든 '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); 

} 
+2

시도해 보셨습니까? 예를 들어'printf (format, ...);가'fprintf (stdout, format, ...)와 동일하다 '는 것을 알게되면 파일에 함수의 인자를 처리하게 할 수 있습니다.'void process (파일 * outfile) {...}'. BTW, ['while (! feof())'는 거의 항상 잘못되었습니다.] (https://stackoverflow.com/q/5431941/1270789). –

+0

안녕 @ KenY-N, 나는 해봤이 : 무효 요약 (무효) =하면 fopen reportfile { ("C : \\ 클래스 \\ mod5 \\ 예 \\ eweinrot_ie.txt", "w") ; fprintf (보고서 파일, "... ... \ n"); fprintf (보고서 파일, "550 ... \ n"); fprintf (신고 파일, "Palm ... \ n \ n"); fprintf (보고 파일, "유형 금액 Net \ n"); fprintf (reportfile, "---- ------ --- \ n"); fprintf (reportfile, "% s % 15.2f % 17.fprintf (보고서 파일, "\ n 해당 월의 순 총액은 $ % 1.2f \ n 처리 된 거래 : % d \ n", 총계, 총계) fclose (reportfile) ; } – davidw

+0

부동 소수점을 금전적 값으로 사용하지 말고 필요하다면 정말로 'float'을 피하십시오. 대신 double을 사용하십시오 –

답변

0

사용 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 통화가 메인으로 이동한다면, 거의 다수의 개구부 비효율적 인 코드(). FILE * reportfile을 고려할 때 fprintf 호출을 변경하여 보고 파일 대신 대신을 쓰는 것 외에는 아무 것도 필요하지 않습니다. 대신 그 fprintf와 전화를 사용

// Produce Report 

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

이 목적을 제공한다 코드 시퀀스 아래 호출하기 전에

가까운 로직이 코드

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

을 다시 열

man -a dup 

P.S - 다른 플랫폼에서는 꽤 많은 리눅스 코드가 테스트되지 않았습니다.

+0

'header()'와'summary()'함수도 있습니다. 그리고 파일을 열게하는 것은 적어도 비효율적 일 것입니다. –