How to use the constant #defined as the maximum field width in fscanf?

All this on C89, not on C99.

I have a constant.

#define MAX_NAME_LEN 256

I want to use it as the maximum field width in fscanf, sort of like.

fscanf(input, "%256s", name);

But I want to use MAX_NAME_LEN instead of literal 256 for a good style. I tried everything

fscanf(input, "%MAX_NAME_LENs", name);

char* max_name_len_str = malloc(16 * sizeof *max_name_len_str);
sprintf(max_name_len_str, "%d", MAX_NAME_LEN);
fscanf(input, "%" max_name_len_str "s", name);
free(max_name_len_str);

//works with printf, but has different meaning in scanf
fscanf(input, "%*s", MAX_NAME_LEN, name);

fscanf(input, "%%ds", MAX_NAME_LEN, name);

without success.

char* nameFormat = malloc(16 * sizeof *nameFormat); //I assume I don't ever want more than 10^13 characters in a name
sprintf(nameFormat, "%s%ds", "%", MAX_NAME_LEN);
fscanf(input, nameFormat, name);
free(nameFormat);

really works, but awkward as everyone is coming out. Is there a more elegant solution?

+6
source share
4 answers

1st simplification.

// Unlikely need to malloc short array
char nameFormat[16]; // I assume I don't ever want more than 10^13 characters  
sprintf(nameFormat, "%%%ds", MAX_NAME_LEN);  // %% prints a %
fscanf(input, nameFormat, name);

Second suggestion or better, use stringify @DevilaN .
Note that the buffer size must be at least 1 larger than the width "%s".

#define MAX_NAME_LEN 256
#define MAX_NAME_LEN_STR "256"

char name[MAX_NAME_LEN + 1];
fscanf(input, "%" MAX_NAME_LEN_STR "s", name);

3rd, fgets() ( ). , , . .

#define MAX_NAME_LEN 256
char name[MAX_NAME_LEN + 2];
fgets(name, sizeof name, input);
+3

:

#define STRINGIFY(X) INDIRECT(X)
#define INDIRECT(X) #X

:

#define MAX 10
puts("%"STRINGIFY(MAX)"d");

%10d.

char name[MAX_NAME_LEN + 1];
fscanf(input, "%"STRINGIFY(MAX_NAME_LEN)"s", name);

# ( ") , . , .
MAX_NAME_LEN 256. INDIRECT(MAX_NAME_LEN) "MAX_NAME_LEN".

+4

fscanf. , , fscanf.

fgets, :

#define MAX_NAME_LEN 25

int main()
{
        char string[MAX_NAME_LEN];
        fgets(string,MAX_NAME_LEN,stdin);

        printf("%s", string);

}
0

fscanf_s() , VS, C99. unsigned name[] . VS 2015.

char name[MAX_NAME_LEN + 1];
fscanf_s(input, "%s", name, (unsigned) sizeof name);

C11 fscanf_s() K, , , . C11 rsize_t/size_t.

fscanf_s(input, "%s", name, sizeof name);

256 , . fscanf() EOF. , VS . , , .


Any of them is slightly different from the one below, since additional text is not readable in name[], so buffer overflow does not occur. Any additional text remains for the next function call. fscanf()returns 1.

fscanf(input, "%256s", name);
0
source

All Articles