我无法使用c ++(codeblocks)中的fstream将文件内容复制到另一个。我该如何运行该文件?

问题描述 投票:1回答:1

我试图从一个文件复制到另一个文件,但我没有在程序结束时没有输出,没有任何错误。在下面的程序中,我首先尝试使用内容名称,rollno,年龄等创建一个文件(details.txt)。这部分代码似乎有效。该程序的其余部分似乎根本不起作用,即创建第二个文件并将文件的内容复制到char指针Textfile。稍后将文件移动到第二个文件(detailscpy.txt)。我按照老师的指示尝试了一些解决方案,但似乎没有用。

  #include<iostream>
#include<fstream>

using namespace std;
int main()
{
    char name[25];
    char rollno[25];
    int age;
    char nation[20];
    char course[30];
    char* textfile;
    fstream file;
    fstream filecpy;


    cout<<"Enter your name: ";
    cin.getline(name,25);
    cout<<"Enter the course you have enrolled: ";
    cin.getline(course,30);
    cout<<"Enter your rollno: ";
    cin.getline(rollno,20);
    cout<<"Enter your age: ";
    cin>>age;
    cout<<"Enter your nationality: ";
    cin>>nation;


    file.open("details.txt",ios::out);
    if(!file)
    {
      cout<<"Error in creating file.."<<endl;
      return 0;
    }
    cout<<"File created successfully"<<endl;
    file<<name<<endl<<rollno<<endl<<age<<endl<<nation<<endl<<course;

file.close();

    filecpy.open("detailscpy.txt",ios::out);
    if(!filecpy)
    {
        cout<<"error is creating a copy file"<<endl;
        return 0;
    }
    cout<<"Copy file created successfully"<<endl;

   file.open("details.txt", ios::in );

    while(file)
    {


        file>>textfile;
        cout<<textfile;

        filecpy<<textfile<<endl;
    }

        file.close();

    filecpy.close();

    return 0;


}



enter code here
c++ file fstream
1个回答
1
投票

你还没有为你的指针char* textfile;分配任何内存。不要以为这会自动发生。因为你使用的是一个未初始化的指针,你的代码有不确定的行为,我很惊讶它并没有崩溃。

复制文件的一种简单直接的方法是一次一个字符。

char ch;
while (file.get(ch)) // read one character
{
    filecpy.put(ch); // and write it out
}
© www.soinside.com 2019 - 2024. All rights reserved.