Reading file line by line
Reading file line by line
Ok here what i want to do. I have a file named myfile.txt i want to pick a random number and have it read that line of the file.
EX.
hhhhh
jjjjjjjj
kkkkk
lllllllllll
yyyyy
tttttttt
and i want to pull out line 4 and store it in a variable so that
variable == lllllllllll
If this would be easier with an ini then please tell me.
EX.
hhhhh
jjjjjjjj
kkkkk
lllllllllll
yyyyy
tttttttt
and i want to pull out line 4 and store it in a variable so that
variable == lllllllllll
If this would be easier with an ini then please tell me.
Just as i had said and psoted on psp-programming.com...
Complied and tested WORKING via Dev-C++, if you wish to use this on the PSP, change getch(); to the sceKIernelSleepThread(); or delay, or whatever... Also, as you cna tell, the line number being read is fed into the buffer named 'buffer' so...
oh and to get a random line number from the file, then do this, since at psp-rpogramming you asked for random, AKA doing your ENTIRE code for you :(
Code: Select all
#include <stdio.h>
// what line to go to: 5 as example
#define GotoLine 5
// do not touch below
#define lineNumber 0
int main() {
char string[1000];
int z;
FILE * pFile;
long lSize;
char * buffer;
pFile = fopen ( "myfile.txt" , "rb");
printf("File Opened Successuflly\n");
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (lSize);
for ( z=lineNumber; z<GotoLine; z++ ) {
fgets(buffer, lSize, pFile);
}
printf("%s", buffer);
getch();
return 0;
}
oh and to get a random line number from the file, then do this, since at psp-rpogramming you asked for random, AKA doing your ENTIRE code for you :(
Code: Select all
#include <stdio.h>
#define GotoLine rand()%100
int main() {
char string[1000];
int lineNumber = 0, z;
FILE * pFile;
long lSize;
char * buffer;
srand(time());
pFile = fopen ( "myfile.txt" , "rb");
printf("File Opened Successuflly\n");
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (lSize);
for ( z=lineNumber; z<GotoLine; z++ ) {
fgets(buffer, lSize, pFile);
}
printf("%s", buffer);
getch();
return 0;
}
You may also want inform him that GotoLine definition assumes there are 100 lines in the file...
And leave populating this with the actual number of lines in the file as an exercise for the reader ;)sg57 wrote:Code: Select all
#define GotoLine rand()%100
--( someone stole my sig! )--
well at psp-programming.com he had asked for something that will read a file line by line, when having like 5 lines in it, so i just assumed 100 for guessing. And theres a way to first get the number of lines in a file then have it done automaticaly... Use a loop,
while ( gets(file) 1= '\0') { puts(file); LineCount++; }
while ( gets(file) 1= '\0') { puts(file); LineCount++; }