【问题标题】:Open a file, modify every char then do the reverse operation doesn't output the original file打开一个文件,修改每个字符然后做反向操作不输出原始文件
【发布时间】:2017-10-04 18:53:40
【问题描述】:
#include <fstream>

int main()
{
    // compress

    std::ifstream inFile("test.input");
    std::ofstream outFile("test.compressed");
    char c;

    while(inFile >> c)
        outFile << c + 1;

    // decompress

    std::ifstream inFile2("test.compressed");
    std::ofstream outFile2("test.output");

    while(inFile2 >> c)
        outFile2 << c - 1;

    // close

    inFile.close();
    outFile.close();
    inFile2.close();
    outFile2.close();

    return 0;
}

这是我的代码。可能有些东西我不明白,因为对我来说test.input 应该与test.output 相同,但它们不是。

【问题讨论】:

  • 如果你要打开一个ifstream 到一个你已经有一个ofstream 句柄的文件,首先刷新它。在开始任何与减压相关的事情之前,请致电outFile.flush()
  • 更好的是,不要将物品放置在周围超过需要的时间。将压缩代码括在大括号中(或移动到另一个函数),然后对解压缩代码执行相同操作。此外,您可以依靠流析构函数以这种方式关闭文件,无需显式调用close
  • “做反向操作”是什么意思?

标签: c++ file char fstream


【解决方案1】:

这里有两个问题。首先,当您从int 中添加(或减去)char 时,结果是int。所以计算c + 1 将作为数字写入test.compressed(例如,'a' 的 ASCII 码是97。所以在将1 添加到它之后你会得到98,它将被写入文件作为字符'9''8')。然后从这些字符中减去 1,显然不会得到相同的输出。这可以通过将结果转换回char 来解决。

第二个问题更加平淡无奇 - 您尝试在刷新之前读取已写入的文件,因此您可能会丢失部分(或全部)已写入的数据。这可以通过在完成文件后关闭文件来解决,这通常是一个好习惯。

把它们放在一起:

#include <fstream>

int main()
{
    // compress

    std::ifstream inFile("test.input");
    std::ofstream outFile("test.compressed");
    char c;

    while(inFile >> c)
        outFile << (char)(c + 1); // Casting to char

    // Close the files you're done with
    inFile.close();
    outFile.close();

    // decompress

    std::ifstream inFile2("test.compressed");
    std::ofstream outFile2("test.output");

    while(inFile2 >> c)
        outFile2 << (char)(c - 1); // You need the cast here too

    // Close the files you're done with
    inFile2.close();
    outFile2.close();

    return 0;
}

【讨论】:

  • 谢谢!实际上,我认为将整数打印到文件中会将其视为字符。虽然它仍然不起作用,但我不明白为什么:如果我在第一个 while 和第二个 std::cout &lt;&lt; (char)(c - 1) &lt;&lt; " "; 中打印字符 std::cout &lt;&lt; (char)(c + 1) &lt;&lt; " ";,它不会显示相同的字符。
  • 那是因为您还需要从空格中减去 1,而不是向它们添加 1。阅读文件时需要跳过空格。
  • 好吧,即使没有&lt;&lt; " ",这两个while 也不会打印相同的东西。
  • @Jeremy 你能分享一个输入和输出的例子吗?当我使用微不足道的输入 (abcdefg) 对其进行测试时,上述代码有效。
  • 我尝试使用 .jpeg 文件作为输入,但它应该可以正常工作吗?它只是字节。是否有可能一个文件考虑从 -128 到 127 的字符,而另一个文件考虑从 0 到 255 的字符?或者如果一个字符在上限,当我添加+1然后-1时,它仍然在上限吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多