当将文件附加到另一个奇怪的符号出现在结尾时它的ascii是-1,如果有另一种方法将文件添加到另一个请分享
void AddFile(char old_name[],char old_content[]) {
ofstream old_file;
ifstream new_file;
char new_name[255];
int len, f_begin, f_end;
cout << "Enter the file name: ";
cin.ignore();
cin.getline(new_name,255,'\n');
strcat(new_name, ".txt");
new_file.open(new_name);
f_begin = new_file.tellg();
new_file.seekg(0,ios::end);
f_end = new_file.tellg();
new_file.seekg(0);
len = f_end - f_begin;
char new_content[len+1];
new_content[len] = '\0';
for (int i=0; i< len; ++i) {
new_content[i] = new_file.get();
}
new_file.close();
strcat(old_content,"\n");
strcat(old_content,new_content);
old_file.open(old_name);
cout << old_content;
old_file << old_content;
old_file.close();
}
.tellg()函数给出正确的大小
答案 0 :(得分:0)
我只写了一段代码来帮助您朝着正确的方向前进。您可以使用它或根据需要进行修改。
#include <iostream>
#include <fstream>
using namespace std;
void AddFile(char old_name[], char old_content[]) {
ofstream old_file;
ifstream new_file;
char new_name[255];
int len, f_begin, f_end;
cout << "Enter the file name: ";
/*cin.ignore();
cin.getline(new_name, 255, '\n');*/
cin >> new_name;
strcat(new_name, ".txt");
new_file.open(new_name);
old_file.open(old_name, ios::ios_base::app);
char line[65535];
while (new_file.getline(line, 65535))
{
old_file << endl << line;
}
new_file.close();
old_file.close();
//verify new data
new_file.open(old_name);
while (new_file.getline(line, 65535))
{
cout << line << endl;
}
}
void main()
{
AddFile("hello.txt", "old data");
}
如果你可以分享你的用例,我可以提供更好的帮助。