Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Urgent !!! : how to read a text file in vc++

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
how to read a text file in vc++.

Thanks
 
Hi

You can read a file in C++ in many ways. One of the ways I use is as follows (this also works in C).

FILE *fPtr;

fPtr.fopen("filename", "r");
.
.
fPtr.close();

To access the data in the file you can use:

char c = fgetc(fPtr); // gets a byte at a time

or

fread(...); // reads into a buffer setup by you

If you need any extra info just reply to this.

Good luck
 
Hi

You can use MFC base class to do it:

CString strContent = "";
CFile fRec;
CFileException e;
CString strUnit;

if ( !fRec.Open( strFile, CFile::modeRead | CFile::shareDenyNone, &e))
{
CString strMsg;

strMsg.Format( "Unable to Open File %s: error %d", strFile, e.m_cause);

AfxMessageBox( strMsg);

return .... what you want .. FALSE, ...
}

int nLength = ( int) fRec.GetLength();

// Allocate Memory to Read File

char* pszBuffer = new char [nLength + 1];

if ( pszBuffer == ( char*) NULL)
{
fRec.Close();

AfxMessageBox( "Memory Allocation Error !!! Unable to Read ...");

return .... what you want .. FALSE, ...
}

// Read File

fRec.Read( pszBuffer, nLength);

// Clean Up

fRec.Close();

You can store it in a CString

strContent = CString( pszBuffer, nLength);

Do not Forget to Clean up memory ...

// Free Memory

delete [] pszBuffer;

HTH

Thierry
EMail: Thierry.Marneffe@swing.be





 
You can also use STL:
#include<fstream>
int main()
{
ifstream oneFile(&quot;OneFile.txt&quot;);
go on;
return 0;
} John Fill
1c.bmp


ivfmd@mail.md
 
You can also use STL:
#include<fstream>
using namespace std;
int main()
{
ifstream oneFile(&quot;OneFile.txt&quot;);
go on;
return 0;
} John Fill
1c.bmp


ivfmd@mail.md
 
If you want to read it in char by char then use the get() method.
or line by line with getline()
 
You can also use plain win32 calls. For example, this will read in a file &quot;C:\test.txt&quot; and display it in a message box:

#include <windows.h>

int main()
{
DWORD dwSize, dwBytesRead;
HANDLE hFile = CreateFile(&quot;c:\\test.txt&quot;, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
dwSize = GetFileSize(hFile, NULL);
char* pFileText = new char[dwSize + 1];
pFileText[dwSize] = 0;
if (ReadFile(hFile, pFileText, dwSize, &dwBytesRead, NULL))
MessageBox(0, pFileText, &quot;&quot;, 0);
delete pFileText;
}
CloseHandle(hFile);
return 0;
}
--Will Duty
wduty@radicalfringe.com

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top