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

I can't copy file content to another using fstream in c++(codeblocks). How can I run the file?

本文关键字:文件 另一个 复制 何运行 运行 c++ 代码 fstream 中的      更新时间:2023-10-16

我尝试将一个文件复制到另一个文件,但是在程序结束时我没有输出,该输出正在运行而没有任何错误。在以下程序中,我首先尝试使用内容名称,rollno,年龄等创建一个文件(lidets.txt)。代码的这一部分似乎可以使用。该程序的其余部分似乎根本没有用来创建第二个文件并将文件的内容复制到Char Pointer TextFile。稍后将文件移至第二个文件(litesscpy.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

您尚未为指针char* textfile;分配任何内存。不要认为这会自动发生。因此,由于您使用的是非初始化的指针,您的代码具有不确定的行为,我很惊讶它没有崩溃。

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

char ch;
while (file.get(ch)) // read one character
{
    filecpy.put(ch); // and write it out
}
相关文章: