C语言从一个文件读数据到写入另一个文件

sprintf(dsp_buf, "%02d%-20s%-15s%-8s%-5s%2s%6s%12s %06s%06s %6s %6s %12s %d\n"
, trans_type, f_card_no, merchant_no, terminal_id
, date_exp, resp_code, auth_id, amount, time_header
,stime1,sys_trace_num, invoice_v, ref_no,0);
以上是我需要读的文件的每一行的格式,我只需要merchant_no, terminal_id,amount,要求计算每个商户(merchant_no)下的每个终端(terminal_id)的交易金额(amount)。然后根据商户号写入到一个TXT文件中。注:一个商户下面可能有多个终端,要求计算出每个终端的交易金额。
一行的数据大概是这样的:
021234567890123456 104110054111335110064381212 00666666000001560000 131230121344 888888 777777 123456789012 0

你可以模仿者写下,atoi()//可以把字符串变成数字

//比如atoi(“1234”)=1234,下面输出的是我的文当格式

#include<iostream>

using namespace std;

void read()

{

FILE *fp;

char n1[20],n2[20],n3[20],n4[20];

int a,b,c,d;

if((fp=fopen("date.txt","r"))==NULL)

{

cout<<"can not open the file\n";

exit(0);

}

fscanf(fp,"%s\n",n1);


a=atoi(n1);//把字符串转变成数字

cout<<a<<endl;

while(!feof(fp))

{

fscanf(fp,"%s%s%s%s\n",n1,n2,n3,n4);

cout<<n1<<"    "<<n2<<"    "<<n3<<"    "<<n4<<endl;

}


}

void main()

{

read();

}

追问

关键我现在需要把商户号和金额先从文件里面拿出来! 一个商户号对应一个总金额!

追答

merchant_no 和 amount是不?
格式都是sprintf(dsp_buf, "%02d%-20s%-15s%-8s%-5s%2s%6s%12s %06s%06s %6s %6s %12s %d\n" , trans_type, f_card_no, merchant_no, terminal_id , date_exp, resp_code, auth_id, amount, time_header ,stime1,sys_trace_num, invoice_v, ref_no,0);
是吗

追问

是的,现在我只能取出一条数据 上面那一串数字就是数据格式了

追答#include<stdio.h>
#include<iostream>
void main()
{
FILE * fp;
if((fp=fopen("客户.txt","r"))==NULL)
{
printf("打开文件错误\n");
exit(0);
}
char trans_type[20],f_card_no[20],merchant_no[20],terminal_id[20],date_exp[20],resp_code[20],auth_id[20],
amount[20],time_header[20],stime1[20],sys_trace_num[20],invoice_v[20],ref_no[20],nn[20];
fscanf( fp ,"%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n" , trans_type, f_card_no, merchant_no, terminal_id, date_exp, resp_code, auth_id, amount, time_header ,stime1,sys_trace_num, invoice_v, ref_no,nn);
}
///这就把所有的信息都取出来了,你想使用那条信息就是用那条
//atoi()//可以把字符串变成数字
//比如atoi(“1234”)=1234,

追问

扣474210904 给你看看我的代码 谢谢

追答

你可以通过私信发过来

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-09-26

可以通过fgetc函数,依次读取源文件的每个字节,再写入到目标文件,直到文件尾为止。

流程为:

1 打开文件,源文件采用读方式,目标文件采用写方式;

2 循环逐字节读取数据,并写入目标文件;

3 当遇到文件尾(EOF)时退出循环;

4 关闭文件。


写成代码为:

void file_copy(char *src, char *dst)
{
    int c;
    FILE *s = NULL,*d=NULL;
    s = fopen(src, "r");
    d = fopen(dst, "w");//打开文件。
    if(s == NULL || d == NULL)//打开文件失败。
    {
        if(s)fclose(s);
        if(d) fclose(d);
        return;
    }
    while((c = fgetc(s))!=EOF)//循环读文件到文件尾。
        fputc(c, d);//写目标文件。
    fclose(s);
    fclose(d);//关闭文件。
}

第2个回答  2018-05-07
你用int型的变量能这样将文件中的内容读入到另一个文件?用char型的一个数组不好吗?
相似回答