【问题标题】:file structure in c++c++中的文件结构
【发布时间】:2018-05-11 18:48:06
【问题描述】:

直截了当我的问题是:如何让文件指针指向下一行?以下是我整个程序的一部分:

         void filewrite(fstream &f2)
         {
            f2.seekp(0,ios::beg);
            f2.write(customerno,strlen(customerno));
            f2.seekp(24,ios::beg);
            f2.write(customername,strlen(customername));
            f2.seekp(56,ios::beg);
            f2.write(product,strlen(product));
            f2<<endl;
         }

这里 f2 是文件指针 customerno、customername 和 product 是字符串 0,24 和 56 分别是这些字符串从头开始的位置

我面临的问题是,每次我尝试写一条新记录时,它都会写完前一条,而不是进入下一行。

我希望每条新记录与第 0、第 24 和第 56 位对齐。 我该怎么做? 提前致谢。

【问题讨论】:

  • 是否有理由需要每个字符串位于特定位置?您可以只使用空格分隔的方法。
  • 是的,这很重要!
  • 你能把你调用这个函数的部分代码贴出来吗?另外,为什么间距很重要?
  • seekp 给出输出流中的位置。因此,每次调用此函数时都会覆盖相同的位置。
  • 您没有写入终止 NUL,因此当您读回字符串时,您将无法确定字符串的长度。

标签: c++ filestructure


【解决方案1】:

如果你使用这种方法,你就是给自己一个具有挑战性的问题。您想使用std::setw() 为您执行此操作。

这是一个更简单的方法:

#include <fstream>
#include <iomanip>
using namespace std; 
void filewrite(ofstream &f, string customerno, string customername, string product)
{
   f << left << setw(24) << customerno << setw(32) << customername << product << endl;
}

【讨论】:

  • 嘿,非常感谢安德鲁。但我还有另一个问题。指针仍然没有转到下一行。光标回到左上角,即行首。 :(请帮帮我
  • 我在发布之前测试了代码并且它有效。你能用你的称呼来更新你的问题吗?
【解决方案2】:

我不知道,如果我的问题是正确的,但如果你想确保在当前行内寻找,你可以这样做:

void filewrite(fstream &f2)
{
  long pos = f2.tellp();

  f2.seekp(pos + 0);
  f2.write(customerno,strlen(customerno));
  f2.seekp(pos + 24);
  f2.write(customername,strlen(customername));
  f2.seekp(pos + 56);
  f2.write(product,strlen(product));
  f2<<endl;
}

这只能按预期工作,但如果您可以确保调用函数 filewrite 时文件流位于下一行的开头。

否则我会很复杂地找到光标在流中的正确位置。

【讨论】:

  • 确保第一次调用此方法时 pos 为 0。另外,请注意,此代码不会编译,因为变量超出范围。
  • Andrue,感谢您的反馈。没错,我在函数前加了三个全局变量,让这段代码sn-p编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2020-11-01
  • 1970-01-01
相关资源
最近更新 更多