Reputation: 191
I'm really new to C, so sorry if this is a dumb question but let's say I have a file containing the following:
1 abc
2 def
3 ghi
If I pass in an integer like 3 (Or character?) the function will return a string of "ghi". I don't know how to make this happen.
void testFunc(int num)
{
FILE *fp;
fp = fopen("testfile.txt", "r");
if(strstr??????
}
Yea.. I have no idea what I'm doing. Can anybody offer any guidance?
Upvotes: 0
Views: 125
Reputation: 382
Use fgets to read each line Use sscanf to save the first and second elements of each line to variables Test whether the number = 3, and if so print the word.
The man pages should give you all the info you need to use fgets and sscanf
Upvotes: 1
Reputation: 40155
//input:num, output:string, string is call side cstring area.
void testFunc(int num, char *string){
FILE *fp;
int n;
fp = fopen("data.txt", "r");
while(2==fscanf(fp, "%d %s ", &n, string)){
if(num == n){
printf("%s\n",string);
break;
}
}
fclose(fp);
return;
}
Upvotes: 0
Reputation: 484
You can follow this link, you can do a bit google also. Its really simple you should try your own once. Reading c file line by line using fgetc()
Upvotes: 2
Reputation: 17595
Try this code
void testFunc(int num)
{
FILE *file = fopen ( "testfile.txt", "r" );
char line [ 128 ]; /* or other suitable maximum line size */
if ( file != NULL )
{
while ( fgets ( line, sizeof(line), file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
}
Upvotes: 0