fread question

Started by
13 comments, last by CProgrammer 20 years, 11 months ago
When i read in a text file using fread how do i get the char* i obtain to be nullterminated. I mean how do i have it stop copying after the text in the text file is done. -CProgrammer
Advertisement
fread? im not sure i'v heard of it but


    #include <fstream.h>void main(){	const int MAX = 80;	char buffer[MAX+1];	ifstream aFileReader("sample.txt");	while (aFileReader)	{		aFileReader.getline(buffer, MAX, '\n'); // When it reaches a line, stop, display		cout << buffer << endl;;		// Manually endl and continue	}};    


[edited by - Malpass on May 4, 2003 6:38:42 AM]
fread is binary, you want fscanf or fgets
fgets didnt quite do it for me since it only reads in one line. It has to be able to read in a text of many lines.
malpass: same need many lines.
You know a similar function for that.
fscanf didnt work at all. Dont know why.
Is there a function for this or must a use a string tokenizer and add a special ending sign to my text.
-CProgrammer
quote:Original post by malpass
...


Oh, come on. If you are going to show them the "C++" way, at least show it to them properly:      


#include <iostream>
#include <fstream>
#include <string>

int main()
{
std::ifstream inFile("sample.txt");

std::string line;
while (inFile)
{
std::getline(inFile, line, '\n');
std::cout << line << std::endl;
}

...

inFile.close();

return 0;
}


[ Google || Start Here || ACCU || MSDN || STL || GameCoding || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on May 4, 2003 4:42:40 PM]
[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || [email=lektrix@barrysworld.com]E-Mail Me[/email] ]
sooooooooooooorrry... I dont even program C++, i use C#, I was only trying to help, and the only thing wrong with mine was it didnt include the iostream, WHICH if u knew isnt even nesseccery, it included in fstream
Hehe. The difference is the use of std::string.

[ Google || Start Here || ACCU || MSDN || STL || GameCoding || BarrysWorld || E-Mail Me ]
[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || [email=lektrix@barrysworld.com]E-Mail Me[/email] ]
Hey thanks everybody.

-CProgrammer
Oh and because im used to C in matters like these.
I have another question.
How do i convert std::string to char*?

-CProgrammer
quote:Original post by CProgrammer
Oh and because im used to C in matters like these.
I have another question.
How do i convert std::string to char*?

-CProgrammer

const char * TheCharStar = AnStdString.c_str();

if you want one that you can modify, its a bit trickier:

char * TheCharStar = new char[AnStdString.length() + 1];
strcpy(TheCharStar, AnStdString.c_str(), AnStdString.length());

This topic is closed to new replies.

Advertisement