Is there a way to read from a text file, more than the first line?
I tried fgets, but I don't know how to continue on the next line, fscanf screws up if it encounters a space ' '. I just need to find a way to get this done.
can anyone help?
Is there a way to read from a text file, more than the first line?
I tried fgets, but I don't know how to continue on the next line, fscanf screws up if it encounters a space ' '. I just need to find a way to get this done.
can anyone help?
Last edited by sea_4_ever; 08-26-2007 at 12:43 AM. Reason: missed a word
Don't answer all at once!
really.
this isn't irc, have patience.
why not just call fgets again?
Wow, 28 minutes, and you complain you didn't get an answer. Might I echo the same sentiments as robwhit and suggest some patience?
Or how about something better. If you're going to complain that we haven't done your work for you in less than half an hour, how about you apply your energy and impatience to researching it youself?
What's wrong with calling fgets() in a loop? Or as the condition?
If you want to quit when you read a certain line, break when you encounter it.Code:char szBuffer[BUFSIZ]; FILE *somefile; ... /* Assume somefile has been initialized and is a valid, open file for reading. */ while(fgets(szBuffer, sizeof(szBuffer), somefile)) { /* process data read into szBuffer */ }
If you want to read the whole file, just use fread():
Code:#include <stdio.h> #include <malloc.h> int main() { long length; char* buf; size_t bytes; FILE* file = fopen( "c:/file.txt", "rb" ); if ( file == NULL ) { printf( "Error opening file!" ); return 1; } if ( fseek( file, 0, SEEK_END ) != 0 ) { fclose( file ); printf( "fseek() failed!" ); return 2; } if ( (length = ftell( file )) < 0 ) { fclose( file ); printf( "ftell() failed!" ); return 3; } if ( fseek( file, 0, SEEK_SET ) != 0 ) { fclose( file ); printf( "fseek() failed!" ); return 2; } if ( (buf = malloc( length + 1 )) == NULL ) { fclose( file ); printf( "malloc() failed!" ); return 4; } if ( (bytes = fread( buf, 1, length, file )) != (size_t)length ) { free( buf ); fclose( file ); printf( "fread() didn't read %d bytes!", length ); return 5; } fclose( file ); buf[length] = '\0'; printf( "Text file contents:\n%s", buf ); free( buf ); return 0; }
Last edited by cpjust; 08-26-2007 at 03:17 PM. Reason: Oops, forgot to free( buf )...
Alright, I have a something working, thanks for all the help.
Now, I JUST figured out the "get input without pressing enter" thing, and have a good idea of how it works, now to practice it, I need to make some kind of game using the directional keys to navigate.
Any ideas on an easy game to make?
I was thinking some kind of Maze, or tic-tac-toe.
use stdlib.h instead. malloc.h is not standard.Code:#include <malloc.h>http://faq.cprogramming.com/cgi-bin/...&id=1043284392Code:FILE* file = fopen( "c:\\file.txt", "rb" );
robwhit, I already know how.
I just need to think of what game to make.