user10967362
user10967362

Reputation: 97

How to read all the content which is stored into a txt file?

How to read all the content which is stored into a txt file?

If I have a txt file with words in it and I want to read all of them and store them into a string how can I do it?

If I use fscanf(in, "%s", string) I only read the first word and when there is the first white space the fscanf stops its job. How can I read all of the words and store them in a string?

Upvotes: 1

Views: 63

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21572

If you're asking how to slurp the entire contents of a file into a single buffer in memory, here's one way (assuming sufficient space in memory):

FILE *fp;
char *buffer = NULL;
size_t len, num_read;

fp = fopen("myfile", "r");
if(fp == NULL) // handle error...
{}

fseek(fp, 0, SEEK_END);
len = ftell(fp);
rewind(fp);

buffer = malloc(len + 1);
if(buffer == NULL) // handle error...
{}

num_read = fread(buffer, 1, len, fp);
fclose(fp);

buffer[num_read] = '\0';

// buffer now contains the entire content of your file
use(buffer);

free(buffer);
buffer = NULL;

Upvotes: 2

Related Questions