scanf() function with variable amount of parameters, how to implement?


I have a text file (txt) that contains the following values:

12 90

These two values ​​I keep and my variables a and b , that is, a is equal to 12 and b is equal to 90 , and I am using the scanf() function to receive these values ​​from the file as follows:

#include <stdio.h>

int main()
    int a, b;

    scanf("%d %d", &a, &b);

    printf("Valor a = %d, b = %d", a, b);



Value a = 12, b = 90

I run the program with the following command scanfTeste.exe < arquivo.txt at the Windows prompt to run the program.

However, the structure of my file will change, it will have two values ​​or an undetermined amount, see the examples:

  • Example one of the file content: 12 90
  • Example two of the file content: 12 90 33 77

Whereas the values ​​are separated by spaces, to facilitate the reading of the data.

My question:

As you can see the amount of parameters passed to scanf("%d %d ...", &a, &b, ...) changes depending on the amount of values ​​in the line of the file, how can I make the function scanf() receive an amount of parameters according to the amount of values ​​in the file line?


One of the ways is to use normal reading adapting to needs, something like this:

char arquivo[] = "1 2 3 4 5";
int a, b, c, d, e;
sscanf (arquivo, "%d %d %d %d %d", &a, &b, &c, &d, &e);
printf ("%d - %d - %d - %d - %d", a, b, c, d, e);

See it working on ideone . And on I also put it on GitHub for future reference .

Obviously need to use fscanf() which is correct for file and not what I used for easy.

Another possibility, which seems to me the best , if you don't want to create all the variables and make them easier to read would be to read them one by one in a loop. Something like:

int i = 0;
int tamanho = 5;
int array[tamanho];
FILE * arquivo = fopen("file.txt", "r");
while (fscanf(arquivo, "%d", &array[i++]) == 1);

I put it on GitHub for future reference .

You can also do this on variable length lists with vfscanf() giving you more flexibility, allowing you to specify the format of the data that will be received at each of the positions. I've never used it and I don't have the details, but the documentation provides this example:

#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
bool checked_sscanf(int count, const char* buf, const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int rc = vsscanf(buf, fmt, ap);
    return rc == count;
int main(void) {
    int n, m;
    printf("Parsing '1 2'...");
    if(checked_sscanf(2, "1 2", "%d %d", &n, &m)) puts("success");
    else puts("failure");
    printf("Parsing '1 a'...");
    if (checked_sscanf(2, "1 a", "%d %d", &n, &m)) puts("success");
    else puts("failure");

I put it on GitHub for future reference .

Scroll to Top