无法使用 fstream class 在 C++ 中创建文件
Unable to use fstream class to create a file in c++
我发布这个问题是因为我无法在 C++ 中正确实现用于文件处理的 get() 和 put() 函数。我已经尝试在 Google 上搜索可以解决我的问题的答案查询,但仍然找不到..
因此,我发布了以下代码。在以下代码中,我打开一个文本文件进行写入,然后打开同一文件进行读取...
该程序没有给出任何语法错误,但它没有按照我期望的那样运行..
完整代码如下:
/*
* IOOperationsonCharacters.cpp
*
* Created on: 13-Dec-2015
* Author: Suyash Dayal
* Objective: I/O Operations on Characters
*/
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char string[80];
cout<<"Enter a string: ";
cin>>string;
int len = strlen(string);
fstream file; // input and output stream
cout<<"\nOpening the 'TEXT' file and storing the string in it.\n\n";
file.open("TEXT", ios::in | ios::out);
for(int i = 0; i < len; i++)
file.put(string[i]); // put a character to file
file.seekg(0); // go to the start
char ch;
cout<<"Reading the file contents: ";
while(file)
{
file.get(ch); // get a character from file
cout<<ch; // display it on screen
}
return 0;
}
该程序接受字符串的输入但不创建文件 TEXT.. 事实上,如果我使用 ofstream class,它会给出语法错误..
我还附上输出供您阅读..
Enter a string: Suyash
Opening the 'TEXT' file and storing the string in it.
Reading the file contents:
任何形式的帮助将不胜感激...
In fact, if I use ofstream class, it gives an syntactical error..
是的,因为您无法从 output 流中读取任何内容。
在你的情况下,你的问题在于没有处理文件的所有潜在问题。您确定在写入文件之前可以写入该文件吗?
打开后查看:
if(!file) {
std::cerr << "File is not open\n"
//...
}
问题很可能在于没有名为 TEXT 的文件。对于您选择的打开模式,它必须存在。阅读此内容以获取有关不同模式及其行为的信息:http://en.cppreference.com/w/cpp/io/basic_filebuf/open
我发布这个问题是因为我无法在 C++ 中正确实现用于文件处理的 get() 和 put() 函数。我已经尝试在 Google 上搜索可以解决我的问题的答案查询,但仍然找不到..
因此,我发布了以下代码。在以下代码中,我打开一个文本文件进行写入,然后打开同一文件进行读取...
该程序没有给出任何语法错误,但它没有按照我期望的那样运行..
完整代码如下:
/*
* IOOperationsonCharacters.cpp
*
* Created on: 13-Dec-2015
* Author: Suyash Dayal
* Objective: I/O Operations on Characters
*/
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char string[80];
cout<<"Enter a string: ";
cin>>string;
int len = strlen(string);
fstream file; // input and output stream
cout<<"\nOpening the 'TEXT' file and storing the string in it.\n\n";
file.open("TEXT", ios::in | ios::out);
for(int i = 0; i < len; i++)
file.put(string[i]); // put a character to file
file.seekg(0); // go to the start
char ch;
cout<<"Reading the file contents: ";
while(file)
{
file.get(ch); // get a character from file
cout<<ch; // display it on screen
}
return 0;
}
该程序接受字符串的输入但不创建文件 TEXT.. 事实上,如果我使用 ofstream class,它会给出语法错误..
我还附上输出供您阅读..
Enter a string: Suyash
Opening the 'TEXT' file and storing the string in it.
Reading the file contents:
任何形式的帮助将不胜感激...
In fact, if I use ofstream class, it gives an syntactical error..
是的,因为您无法从 output 流中读取任何内容。
在你的情况下,你的问题在于没有处理文件的所有潜在问题。您确定在写入文件之前可以写入该文件吗?
打开后查看:
if(!file) {
std::cerr << "File is not open\n"
//...
}
问题很可能在于没有名为 TEXT 的文件。对于您选择的打开模式,它必须存在。阅读此内容以获取有关不同模式及其行为的信息:http://en.cppreference.com/w/cpp/io/basic_filebuf/open