user3783608
user3783608

Reputation: 867

Read file from stdin C with scanf

I can read file contents from stdin with scanf("%s", &input).

How much space should I be allocating for the input string if I do not know how long the file will be?

Upvotes: 1

Views: 15438

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

You should reverse the question. You allocate a buffer of a defined size and them limit the input, be it with scanf of fgets.

#define SIZE 256
char buf[SIZE];
fgets(buf, SIZE, stdin);

or

scanf("%255s", buf);

and then iterate reading.

The use of fgets instead of scanf depends if your input is line oriented or space separated. And ... RTFM ...

Upvotes: 1

kyflare
kyflare

Reputation: 874

Consider using fgets instead of scanf. scanf can cause overflow, but you can tell to fgets the maximum size you want to read. If you need scanf for the format scanning, you can still use sscanf after fgets.

char * fgets ( char * str, int num, FILE * stream );

Upvotes: 1

Related Questions