在文件中写入退格键 [英] Writing a backspace in a file

查看:154
本文介绍了在文件中写入退格键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(){
std::cout << "Insert file name / or path. \n NOTE: ONLY INPUTS. DELETES PREVIOUS DATA.\nV.6" << std::endl;
std::string filen;
std::cin >> filen;
std::ofstream myFile;
try{
myFile.open(filen, std::ios::out);
}
catch(std::fstream::failure){
std::cout << "Could not open file!\n Make sure the name and data type are valid.";
system("pause");
}
while(true){
    int press = getch();
    if(press == 43) myFile.close();
    if(press == 8){myFile << "\b" << " " << "\b";std::cout << "\b" << " " << "\b" << std::flush;}
    if(press == 13){ myFile << "\n"; std::cout << "\n" << std::flush;}
    if(press != 43 && press != 127 && press != 13 && press != 8){myFile << (char)press;std::cout << (char)press;}
       }
return 0;
}

每当我选择一个文本文件并按退格键,然后检查该文档当我检查文本文档时,会得到如下随机字符:

Whenever I choose a text file and I press backspace, and I check the document and when I check the text document, I get random characters like so:

推荐答案

正如@BoundaryImposition指出的那样,编写 \ b 到您的文件,实际上将二进制退格字符写入您的文件。相反,您可能想要的是 myFile.seekp(-1,std :: ios_base :: cur); 。如果您使用的是Win / Dos机器,则可能需要特别小心'\n'字符,因为它们会被翻译成 0x0d 0x0a 写入文本流时(因此,它们需要找回2个位置而不是1个位置)。

As @BoundaryImposition pointed out already, writing "\b" to your file, will actually write a binary backspace character to your file. What you probably want instead is myFile.seekp(-1, std::ios_base::cur);. If you are on win/dos machine you likely need extra care with '\n' characters because they are translated into 0x0d 0x0a when written to a text stream (thus they require to seek back 2 positions instead of 1).

但是通常,如果您不处理非常大的文件,将内容存储在 std :: string (使用 pop_back 擦除,以便在需要时删除字符),并在完成后将其写入文件。

But generally, if you are not dealing with very huge files, it will be way easier to just store the content in a std::string (using pop_back or erase, to remove characters if needed) and write it to the file when you are finished.

这篇关于在文件中写入退格键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆