c++可以使用fstream-infile从最近使用的ofstream-outfile中收集数据
c++ can an fstream infile be used to gather data from an recently used ofstream outfile?
处理完outfile数据后,我想使用名为infile的fstream变量再次接收该数据。外场完成后,是否可以进行下面这样的操作?我的主要目标是读回随机放在文件中的内容,这样我就可以最终将其处理成一个链表。我测试了一个类似的代码,但结果是零。谢谢
ifstream infile;
string FileName = "Numbers.txt";
infile.open(FileName);
while (infile)
{
infile >> RandomNumber;
cout << RandomNumber << endl;
}
infile.close();
这应该有效if ( infile )
将检查文件是否打开,while ( infile >> RandomNumber )
将获取文件中的所有数字:
ifstream infile;
string FileName = "Numbers.txt";
infile.open(FileName);
if ( infile ) {
while ( infile >> RandomNumber ) {
cout << RandomNumber << endl;
}
}
infile.close();
这不是OP问题的答案,而是针对一系列关于读取文件和解析数据的评论中的一个小对话提供的。这是针对Tony和任何希望使用此类设置的人。这个类中有一些与我的库中的其他类有关的东西,其中一些包括我的Logger,它会将消息记录到文件或控制台,消息类型为Info、Warning、Error或console。我的Logger是从Singleton类派生的,因为每个解决方案只需要一个Logger来处理所有消息。我有一个实用程序类,它处理大多数字符串操作函数,其中构造函数是私有的,所有函数或成员都声明为静态的。该类还依赖于一个ExceptionHandler类,该类将接受std::string或std::ostringstream对象。我的Logger也接受相同的设置。此外,我的一些类还依赖于允许使用多线程的BlockThread类,该类在构造时将创建并初始化CriticalSection,然后进入CriticalSection;在销毁时将离开并销毁CriticalSection。现在,对于这个演示,我将只显示我的FileHandler类以及它的两个派生类型,TextFileReader和TextFileWriter。我有更多派生的FileHandlers,它可以读取纹理文件、自定义数据结构等,可以处理二进制文件,而不是文本文件,但为此,只显示文本文件处理程序。
文件处理程序.h
#ifndef FILE_HANDLER_H
#define FILE_HANDLER_H
namespace util {
//class AssetStorage;
class FileHandler {
protected:
//static AssetStorage* m_pAssetStorage;
std::fstream m_fileStream;
std::string m_strFilePath;
std::string m_strFilenameWithPath;
private:
bool m_bSaveExceptionInLog;
public:
virtual ~FileHandler();
protected:
FileHandler( const std::string& strFilename, bool bSaveExceptionInLog );
void throwError( const std::string& strMessage ) const;
void throwError( const std::ostringstream& strStreamMessage ) const;
bool getString( std::string& str, bool appendPath );
private:
FileHandler( const FileHandler& c ); // Not Implemented
FileHandler& operator=( const FileHandler& c ); // Not Implemented
}; // FileHandler
} // namespace util
文件处理程序.cpp
#include "stdafx.h"
#include "FileHandler.h"
namespace util {
// ----------------------------------------------------------------------------
// FileHandler()
FileHandler::FileHandler( const std::string& strFilename, bool bSaveExceptionInLog ) :
m_bSaveExceptionInLog( bSaveExceptionInLog ),
m_strFilenameWithPath( strFilename ) {
// Extract Path Info If It Exists
std::string::size_type lastIndex = strFilename.find_last_of( "/\" );
if ( lastIndex != std::string::npos ) {
m_strFilePath = strFilename.substr( 0, lastIndex );
}
if ( strFilename.empty() ) {
throw ExceptionHandler( __FUNCTION__ + std::string( " missing filename", m_bSaveExceptionInLog ) );
}
} // FileHandler
// ----------------------------------------------------------------------------
// ~FileHandler
FileHandler::~FileHandler() {
if ( m_fileStream.is_open() ) {
m_fileStream.close();
}
} // ~FileHandler
// ----------------------------------------------------------------------------
// throwError()
void FileHandler::throwError( const std::string& strMessage ) const {
throw ExceptionHandler( "File [" + m_strFilenameWithPath + "] " + strMessage, m_bSaveExceptionInLog );
} // throwError( const std::string )
// ----------------------------------------------------------------------------
// throwError()
void FileHandler::throwError( const std::ostringstream& strStreamMessage ) const {
throwError( strStreamMessage.str() );
} // throwError( const std::ostringstream )
// ----------------------------------------------------------------------------
// getString()
bool FileHandler::getString( std::string& str, bool appendPath ) {
m_fileStream.read( &str[0], str.size() );
if ( m_fileStream.fail() ) {
return false;
}
// Trim Right
str.erase( str.find_first_of( char(0) ) );
if ( appendPath && !m_strFilePath.empty() ) {
// Add Path If One Exixsts
str = m_strFilePath + "/" + str;
}
return true;
} // getString
} // namespace util
TextFileReader.h
#ifndef TEXT_FILE_READER_H
#define TEXT_FILE_READER_H
#include "FileHandler.h"
namespace util {
class TextFileReader : public FileHandler {
private:
public:
explicit TextFileReader( const std::string& strFilename );
// virtual ~TextFileReader(); // Default OK
std::string readAll() const;
bool readLine( std::string& strLine );
private:
TextFileReader( const TextFileReader& c ); // Not Implemented
TextFileReader& operator=( const TextFileReader& c ); // Not Implemented
}; // TextFileReader
} // namespace util
#endif // TEXT_FILE_READER_H
TextFileReader.cpp
#include "stdafx.h"
#include "TextFileReader.h"
namespace util {
// ----------------------------------------------------------------------------
// TextFileReader()
TextFileReader::TextFileReader( const std::string& strFilename ) :
FileHandler( strFilename, true ) {
m_fileStream.open( m_strFilenameWithPath.c_str(), std::ios_base::in );
if ( !m_fileStream.is_open() ) {
throwError( __FUNCTION__ + std::string( " can not open file for reading" ) );
}
} // TextFileReader
// ----------------------------------------------------------------------------
// readAll()
std::string TextFileReader::readAll() const {
std::ostringstream strStream;
strStream << m_fileStream.rdbuf();
return strStream.str();
} // readAll
// ----------------------------------------------------------------------------
// readLine()
// Returns A String Containing The Next Line Of Text Stored In The File
bool TextFileReader::readLine( std::string& strLine ) {
if ( m_fileStream.eof() ) {
return false;
}
std::getline( m_fileStream, strLine );
return true;
} // readLine
} // namespace util
TextFileWriter.h
#ifndef TEXT_FILE_WRITER_H
#define TEXT_FILE_WRITER_H
#include "FileHandler.h"
namespace util {
class TextFileWriter : public FileHandler {
private:
public:
TextFileWriter( const std::string& strFilename, bool bAppendToFile, bool bSaveExceptionInLog = true );
// virtual ~TextFileWriter(); // Default OK
void write( const std::string& str );
private:
TextFileWriter( const TextFileWriter& c ); // Not Implemented
TextFileWriter& operator=( const TextFileWriter& c ); // Not Implemented
}; // TextFileWriter
} // namespace util
#endif // TextFileWriter
TextFileWriter.cpp
#include "stdafx.h"
#include "TextFileWriter.h"
namespace util {
// ----------------------------------------------------------------------------
// TextFileWriter()
TextFileWriter::TextFileWriter( const std::string& strFilename, bool bAppendToFile, bool bSaveExceptionInLog ) :
FileHandler( strFilename, bSaveExceptionInLog ) {
m_fileStream.open( m_strFilenameWithPath.c_str(),
std::ios_base::out | (bAppendToFile ? std::ios_base::app : std::ios_base::trunc) );
if ( !m_fileStream.is_open() ) {
throwError( __FUNCTION__ + std::string( " can not open file for writing" ) );
}
} // TextFileWriter
// ----------------------------------------------------------------------------
// write()
void TextFileWriter::write( const std::string& str ) {
m_fileStream << str;
} // write
} // namespace util
下面是使用FileHandlers的类的一些代码片段。
这是使用FileHandler的类头。它读取文本文件并对其进行解析,以确定要创建哪些GUI对象,加载到内存中,以及如何在屏幕上显示它们。它还将一种GUI类型嵌套为另一种类型的子类型。我不会展示这个类的完整实现,而只展示几个涉及使用FileHandlers的函数。
GuiLoader.h
#ifndef GUI_LOADER_H
#define GUI_LOADER_H
#include "Engine.h"
#include "CommonStructs.h"
#include "Property.h"
#include "TextFileReader.h"
namespace vmk {
class AssetStorage;
class GuiCompositeElement;
class GuiElement;
class GuiLayout;
class GuiRenderable;
class GuiText;
class VisualMko;
class GuiLoader sealed {
friend GuiElement* Engine::loadGui( const std::string& strFilename ) const;
private:
std::string m_strFilename;
util::TextFileReader m_file;
bool m_inBlockComment;
unsigned m_uNumBracesOpened;
unsigned m_uLineNumber; // Keep Track OfLine Number For Error Messages
GuiElement* m_pLastGuiRoot;
std::vector<GuiCompositeElement*> m_vpParents;
std::string m_strLine;
std::unordered_map<std::string, TextureInfo> m_mTextureInfos;
std::unordered_map<std::string, FontFace> m_mFontFace;
FontManager* m_pFontManager;
AssetStorage* m_pAssetStorage;
public:
// virtual ~GuiLoader(); // Default Ok
GuiElement* getRoot() const;
private:
GuiLoader( const std::string& strFilename );
GuiLoader( const GuiLoader& c ); // Not Implemented
GuiLoader& operator=( const GuiLoader& c ); // Not Implemented
bool getNextLine();
std::string getFailedLocation() const;
void removeComments();
void parseGui();
bool handleOpenBrace( unsigned uStartLocation, GuiCompositeElement* pGui );
void addToParent( GuiRenderable* pRenderable ) const;
bool getParameter( std::string strParam, unsigned uStartLocation, std::string& strValue, bool isRequired = true, char endCharacter = ' ' ) const;
void setOptionalParameters( unsigned uStartLocation, GuiElement* pGui ) const;
void getOptionalLayoutParameters( unsigned uStartLocation, glm::ivec2& offsetFromParent, Gui::Alignment& eAlignChildren, glm::uvec2& size, std::string& strId ) const;
void setLayoutParameters( unsigned uStartLocation, GuiLayout* pLayout ) const;
bool getOptionalBackgroundParameters( unsigned uStartLocation, TextureInfo& textureInfo, glm::uvec2& origin ) const;
bool getOptionalBackgroundParameters( unsigned uStartLocation, TextureInfo& textureInfo, glm::uvec2& origin, glm::uvec2& size, bool isRequired = true ) const;
void getRequiredTextParameters( unsigned uStartLocation, FontFace& fontFace, std::string& strText ) const;
void setTextShadowParameters( unsigned uStartLocation, GuiText* pGui ) const;
void setVisualMkoParameters( unsigned uStartLocation, VisualMko* pVisualMko ) const;
}; // GuiLoader
} // namespace vmk
#endif // GUI_LOADER_H
GuiLoader.cpp-仅显示少数部分
#include "stdafx.h"
#include "GuiLoader.h"
#include "AssetStorage.h"
#include "FontManager.h"
#include "Gui.h"
#include "Image2d.h"
#include "Logger.h"
#include "TextureFileReader.h"
#include "Utility.h"
using namespace util;
namespace vmk {
// ----------------------------------------------------------------------------
// GuiLoader()
GuiLoader::GuiLoader( const std::string& strFilename ) :
m_strFilename( strFilename ),
m_file( strFilename ),
m_inBlockComment( false ),
m_uNumBracesOpened( 0 ),
m_uLineNumber( 0 ),
m_pLastGuiRoot( nullptr ),
m_pFontManager( FontManager::get() ),
m_pAssetStorage( AssetStorage::get() ) {
while ( getNextLine() ) {
parseGui();
}
if ( m_uNumBracesOpened > 0 ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << getFailedLocation() << ". Missing " << m_uNumBracesOpened << " closing brace" << ( m_uNumBracesOpened > 1 ? "s" : "" ) << ".";
throw ExceptionHandler( strStream );
}
if ( m_inBlockComment ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << getFailedLocation() << ". Missing closing block comment */.";
}
} // GuiLoader
// ----------------------------------------------------------------------------
// getRoot()
GuiElement* GuiLoader::getRoot() const {
return m_pLastGuiRoot;
} // getRoot
// ----------------------------------------------------------------------------
// getNextLine()
// Returns True If Got A Line Of Text (Could Be Blank If It Is All Commented
// Out Or If It Truly Was A Blank Line). False is Returned When There Is
// No More Data In The File
bool GuiLoader::getNextLine() {
if ( !m_file.readLine( m_strLine ) ) {
return false;
}
++m_uLineNumber;
m_strLine = Utility::trim( m_strLine );
//std::cout << m_uLineNumber << ": " << m_strLine << std::endl; // Use This For Debugging The GuiLoader
removeComments();
return true;
} // getNextLine
// ... Other Functions Here
} // namespace vmk
这是为了展示我的文件处理类的健壮性。这里没有显示许多其他类。我的库是使用现代OpenGL的3D图形渲染库的一部分。有几百个类对象和100000行代码用于进行3D图形渲染、精灵加载、物理模拟、动画、音频播放、音频流播放等等。并非所有这些源代码都是我自己设计的,因为这些代码受Marek A.Krzeminski的版权保护,MASc和他的作品可以在www.MarekKnows.com上找到
这里显示的所有代码都不是从他的网站上复制粘贴的,而是在跟随他的视频教程时手动键入的。它是手动编译和调试的。这个项目已经进行了几年,直到今天还在增加更多的项目。自2007-2008年以来,我一直是他的网站和社区的骄傲成员。
int number = 0;
string filename( "Numbers.txt" );
std::ofstream out;
std::ifstream in;
std::cout << "enter a number: << std::endl;
std::cin >> number;
out.open( filename.c_str(), std::ios_base::out );
if ( !out.is_open() ){
// Print, Log Error, Throw Error, Return Etc.
}
for ( int i = 0; i < number; i++ ) {
out << rand() % 100 << std::endl;
}
out.close();
in.open( filename.c_str(), std::ios_base::in );
if ( !in.is_open() ) {
// Error Case Here
}
while ( !in.eof() ) { // Usually bad practice; but my file handling classes are parser objects are too large to show here.
in >> RandomNumber;
std::cout << RandomNumber << endl;
}
infile.close();
- std::ofstream 作为类成员删除复制构造函数?
- ofstream::close() 是否在 Linux 上调用同步?
- 如何在软件代码中使用ofstream创建文件
- Ofstream和IFSTREAM有什么区别?
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- fstream / ifstream / ofstream 对象如何转换为布尔值
- 使用 auto_ptr<std::ofstream> 对象
- 传递数组结构、ofstream 和 interger 以运行
- 有没有办法使用 ofstream 保存屏幕截图?
- 使用 ofstream 写入文本文件时断言失败
- 当 ofstream 指针位于 std::map 中时,文件写入不会发生 C++.
- Ofstream一直给我函数的最后一行,而不是显示所有内容
- 如何将 std::ofstream& 传递给函数参数?
- BigInteger:在 C++ 中使用 ofstream 写入文件时如何将基数更改为 2?
- 数据不是用 ofstream 写入的,即使返回成功也是如此
- ofstream将额外的零字节写入Unix服务器上的文件
- 为什么我不能将 Windows 环境路径与 ofstream 一起使用来编写文本文件?
- 为什么 ofstream 比 fprintf 慢?
- 派生 std::ofstream 和重载运算符<<