c++将一个txt文件中的指定内容复制到另一个txt

2025-03-07 02:05:44
推荐回答(2个)
回答1:

打开文件需要ofstream和ifstream, 一个是读, 一个是写. 所以, 要复制需要这样:

#include 
using namespace std;

int main()
{
    ifstream fin("input.txt");
    ofstream fout("output.txt");
    char data;
    
    if (!fin || !fout)
        return 0;
        
    while(!fin.eof())
    {
        fin>>data;
        fout<    }

    return 0;
}

回答2:

#include
#include
#include
int main()
{
    char buf[1024];
    int rowCount=0;
    int needToRead=3;
    FILE *fpSource=fopen("soure.txt","r");
    FILE *fpDes=fopen("des.txt","w+");
    if(fpSource==NULL)
    {
        puts("error,file can't open\n");
        return -1;
    }
    if(fpDes==NULL)
    {
        puts("error,can't create the file ,or other error");
        return -1;
    }
    
    for(rowCount=0;rowCount    {
        memset(buf,0,sizeof(buf));
        fgets(buf,"%s",fpSource);
        
        fwrite(buf,sizeof(buf),1,fpDes);
    }
    
    fclose(fpSource);
    fclose(fpDes);

    return 0;
}