我无法使用 c++(代码块)中的 fstream 将文件内容复制到另一个。如何运行该文件?
I can't copy file content to another using fstream in c++(codeblocks). How can I run the file?
我尝试将一个文件复制到另一个文件,但是在程序结束时我没有输出,该输出正在运行而没有任何错误。在以下程序中,我首先尝试使用内容名称,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
}
相关文章:
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++ 如何打开带有另一个目录的输入文件?
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 程序在使用 system() 启动另一个可执行文件时停止
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 使用 scope 运算符 (::) 引用另一个文件中的类
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- 使用命名空间在另一个".cpp"文件中定义
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?