user3263115
user3263115

Reputation: 33

read several string from a file

Imagine I have this .txt file:

HEY
What's your name
My name is xx

How i could make, in my C program, to scanf each line into different strings?

Because if I make

fscanf(myfile, "%s", string)

I could only scan word by word, and different lines wouldn't be recognized...

any good way I could do that?

Upvotes: 0

Views: 77

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

e.g

#include <stdio.h>

int main(){
    char string[128];
    FILE *myfile = fopen("data.txt", "r");
    while(1==fscanf(myfile, " %127[^\n]", string)){
        printf("%s\n", string);
    }
    fclose(myfile);
    return 0;
}

Upvotes: 1

ajay
ajay

Reputation: 9680

You can use fgets to read lines successively from a file. However, you must know beforehand the maximum length a line can have.

#define MAX_LEN 100

FILE *fp = fopen("myfile.txt", "r");
char line[MAX_LEN];

while(fgets(line, MAX_LEN, fp) != NULL) {
    // process line
}

fclose(fp);

Here, fgets(line, MAX_LINE, fp) means that fgets will read at most MAX_LINE - 1 bytes from the stream fp and store them in the buffer pointed to by line. One byte is reserved for the null byte which fgets appends in the end. fgets will return if a newline is read which is stored into the buffer line. Therefore, if you want to remove the newline character from line, you should do the following in the above while loop.

line[strlen(line) - 1] = '\0';  // overwrite newline character with null byte

Upvotes: 0

Related Questions