简体   繁体   中英

How do I Extract a part of a line from a file?

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?

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

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

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 );
    }
}
//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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM