【问题标题】:why this code writes can't open file为什么这段代码写不能打开文件
【发布时间】:2010-10-21 19:50:34
【问题描述】:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc,char *argv){
fstream inout("C:\\Users\\7\\Desktop\\test.txt",ios::in | ios::out | ios::binary);
if (!inout){
 cout<<" cannot open input file.\n";
  return 1;

}

long e,i,j;
char c1,c2;
e=5;
 for (i=0,j=e;i<j;i++,j--){


  inout.seekg(i,ios::beg);
  inout.get(c1);
  inout.seekg(j,ios::beg);
  inout.get(c2);
  inout.seekp(i,ios::beg);
  inout.put(c2);
  inout.seekg(j,ios::beg);
  inout.put(c1);
 }


 inout.close();



 return 0;
}

为什么这段代码不能打开文件 编辑: 我已经进行了更正,但这是一个问题 在test.txt中是这样写的

maiko
miyvarxar
shen
me

所以它应该写 me shen miyvarxar 舞妓 但它没有写任何东西 请帮忙

【问题讨论】:

  • 更改您的 cout 行(无法打开输入文件)以打印错误
  • 这真的需要另一个问题吗?它看起来与this one 非常相似。
  • Windows 文件系统(与所有其他现代文件系统一样)现在接受“/”作为目录分隔符。如果您在路径中使用它,它会使代码更具可移植性。更容易阅读(因为它不是逃避)。

标签: c++


【解决方案1】:

这似乎对我有用:

using namespace std;
int main() 
{ 
  fstream inout("C:\\Users\\turdfurguson\\Turds\testfile.txt", ios::in | ios::out | ios::binary);
  if (inout.good())
    cout << "OK!" << endl;
}

如果您有一个可读写的“C:\Users\turdfurgson\Turds\testfile.txt”文件。

【讨论】:

  • 我的桌面完整路径是这个 C:\Users\7\Desktop> 请帮帮我
  • “test.txt”文件是否存在?
  • try ", ios::in | ios::binary); 结果是什么?
  • 天哪,我几乎想为你的名字和路径选择 +1。
【解决方案2】:

您提供的代码看起来不错。

您可能提供了错误的路径或类似的东西。

您也可以尝试以只读模式打开该文件 看看是否可以:

std::ifstream in("path", std::ios::binary);

if (!in) {
   // fail
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    相关资源
    最近更新 更多