0

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?

Giga Tocka
  • 191
  • 3
  • 3
  • 11
  • 1
    "I have no idea" is not good. There's surely **something** that you can come up with. It's not even nevessary to know C. Just think about the algorithm. It's trivial. –  Apr 18 '13 at 04:35
  • Search the www for fopen examples – huysentruitw Apr 18 '13 at 04:37
  • first write a condition to check for character '3'....when this character found you can extract the string after that.. like `while(ch=fgetc(fp)!=EOF) { if(ch=='3') { //extract THE STRING until new line comes. } }` – umang2203 Apr 18 '13 at 04:37

4 Answers4

2

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()

Community
  • 1
  • 1
surender8388
  • 474
  • 3
  • 12
1

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

JWDN
  • 382
  • 3
  • 13
0

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 );
    }
}
Mani
  • 17,549
  • 13
  • 79
  • 100
0
//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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70