PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

File reading

Hi everyone,
I've never really done much file I/O with C++ and I was hoping someone could help me with this. I want to read a file that looks like this:

-1
-1
0
0
0
-1
0

etc.

How can I open that file, and then read the numbers in one by one into integers? Basically, I just need to know how to open the file and read it such that I can read one line at a time and convert it into the proper integer. Can anyone help me?
There are of course several ways to go about it, and several different APIs which can be used. If you want to use stdio for pure portability, then something like this should work:
Code:

FILE *f=fopen("somefile.txt", "r");
if (!f) return; //error opening file
char buf[20];
while (fgets(buf, sizeof(buf), f)) {
int n=atoi(buf);
//do something with n
)
fclose(f);


You might have to strip the last char off the buf string (something like buf[strlen(buf)-1]='\0'; ) if atoi doesn't like buf with a carriage return in it.

Dan East
Dan, I love you.
I will interpret that in the most professional context possible. :)

Dan East
"Everybody loves Dan," a new ABC comedy show, premering Sept 18, 2002.

I laughed, I cried, I learned C++. This is the best damn show ever! God bless you ABC! -Martha Stewert

Ae ure do alote of f***ing cursing on that f***ing owe! I f***ing oved it! -Ozzy Osbourne

Very informative. If we had the money we would buy this show from ABC. But, we can only afford dumb and annoying computer nerds. *sigh* -CEO of TechTV
Dan East wrote:
I will interpret that in the most professional context possible. :)

Dan East


God forbid Dan makes a joke ;)
TechMage - lol. :)

Dan Eeast