【问题标题】:Using fstream to open a file that is created only during runtime使用 fstream 打开仅在运行时创建的文件
【发布时间】:2012-11-20 10:21:12
【问题描述】:

我正在使用 Visual C++ 6.0,并尝试使用 fstream 打开和读取仅在运行时创建的文件。这个文件是由另一个线程上运行的另一个函数编写的,我的程序将继续尝试“打开”文件,直到它可以被打开,即在它被创建之后,然后从中读取 3 个数字并执行它的其余代码。

文件test.txt有内容

1
3
4

我的轮询和打开文件的程序如下:

ifstream fin;
std::string tfile, snum1, snum2, snum3;
long int num2, num3;

tfile.assign(argv[1]);
printf("Begin prog %s\n", tfile.c_str());

fp: fin.open(tfile.c_str(), ifstream::in);
if (fin.is_open())
{
   printf("fin is open\n");
   getline(fin, snum1);
   getline(fin, snum2);
   getline(fin, snum3);
   num2 = atol(snum2.c_str());
   num3 = atol(snum3.c_str());
   printf("snum1 = %s\n", snum1.c_str());
   printf("num2 = %ld num3 = %ld\n", num2, num3);
   fin.close();
}
else
{
   printf("Cannot open file %s\n", tfile.c_str());
   fin.close();
   Sleep(500);
   goto fp;
}

remove(tfile.c_str());
printf("End of prog\n");

我执行了这个程序

test_prog.exe "C:\test.txt"

在将test.txt文件放入C:\之前等待了大约3秒

我的输出是

Begin prog C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
fin is open
snum1 = 
num2 = 0 num3 = 0
End of prog

刷新C:\ 文件夹后,test.txt 文件消失。

所以snum1、num2、num3的值都是错误的,好像文件没有被正确读取一样。

如果我在整个块的 printf("fin is open\n"); 之后放置一个 while fin.good() 循环(直到打印 num2 和 num3 的值),那么我得到

Begin prog C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
Cannot open file C:\test.txt
fin is open
End of prog

如何正确读取仅在运行时创建的文件?

预计到达时间: 我还添加了一个

if (fin.rdstate() & ifstream::failbit) != 0)
   printf("failbit set\n");

在printf("fin is open\n"); 行之后检查,failbit 是在运行时将文件放入文件夹时设置的。

当文件在执行前就位时,一切都会正常运行。

【问题讨论】:

  • 如果您将文件放置到位并然后执行此代码会发生什么?它是否按预期工作?
  • 尝试打开 tfile,而不是 donefile - 另外:提供一个独立的示例,修复警告(long int 需要 %ld,而不是 %d),通常 goto 是一个坏主意(使用while 或类似),使用 ifstream 并进行 c-style-stringprocessing 就像用加载的 Uzi 将某人打死
  • @NPE 是的,如果文件已经在文件夹中,则程序按预期工作。
  • @Peter 我已将“donefile”更改为“tfile”,但仍然得到相同的输出。该程序是由其他人编写的,最初使用 c 风格的编程。但它似乎有一个错误,因此我没有使用 char 数组来存储文件名,而是尝试使用 std::string 和 ifstream。然后我遇到了这个问题。

标签: visual-c++ file-io fstream stdstring


【解决方案1】:

我终于找到了问题。

failbit 在第一个 fin.open 失败后设置,并且在 fin.open 成功后从未重置。一旦我在else 循环中在fin.close() 之后执行fin.clear(),程序运行成功。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    相关资源
    最近更新 更多