Creating a function to read different types of data
I am creating a C99 program and I need help to get rid of a little redundancy in my code. I want to convert the following code into two function calls, but I don't know how.
I want to read two files (each with 15 inputs) and put their contents into two arrays. The problem is that these arrays are of a different data type.
Here's what I have:
typedef char string[30];
int
_vInt[15];
string
_vString[15];
FILE
*_fInt,
*_fString;
int main(){
...
for(int i = 0; !feof(_fInt) && i < 15; ++i){
fscanf(_fInt, "%d", &_vInt[i]);
...
}
for(int i = 0; !feof(_fString) && i < 15; ++i){
fscanf(_fString, "%s", _vString[i]);
...
}
...
}
So, I don't want to use this one for
twice. I'd rather call the function twice instead:
readFile(_fInt, "%d", _vInt);
readFile(_fString, "%s", _vString);
The problem is that I don't know how the function prototype should be, nor how I should use it.
Yes, I'm good at using ugly solutions void *
...
Another solution would be to use the listed types and tables in your readFile () function.
#include <stdlib.h>
#include <stdio.h>
// Put in Header file
typedef char string[30];
typedef enum {
ITInt = 0,
ITString = 1,
ITMax
} InputTypes;
// Should be in module with readFile()
struct inputTypeEntry_s{
const char *format;
size_t sz;
};
struct inputTypeEntry_s inputTypeLUT[ITMax] = {
{ "%d", sizeof(int) }, // ITInt
{ "%s", sizeof(string) }, // ITString
};
int readFile(FILE *fp, InputTypes type, void *data) {
char *ptr = (char *)data;
for(int i = 0; !feof(fp) && i < 15; ++i){
fscanf(fp, inputTypeLUT[type].format, ptr + (i * inputTypeLUT[type].sz) );
}
return 0;
}
source to share
You can extract the type in (void *)
, but it won't.
void foo(FILE *file, const char *format, void *arr, size_t size) {
for(int i = 0; !feof(file) && i < 15; ++i){
fscanf(file, format, ((char *)arr) + (size * i));
...
}
}
The function call will look like
foo(_fInt, "%d", (void *)&_vInt, sizeof(int))
source to share
Since you mentioned that you can use C11 functions, here's an example that uses expressions like C11. I used it to remove the requirement to pass the format string too:
#include <stdio.h>
typedef char string[30];
#define generic_arg(X) _Generic(X, string: X, \
default: &X)
#define generic_format(X) _Generic(X, string: "%s", \
int: "%d")
#define readFile(file, variable) for (int i = 0; i < 15; i++) \
{ \
fscanf(file, \
generic_format(variable[i]), \
generic_arg(variable[i])); \
}
int main(void)
{
int _vInt[15];
string _vString[15];
FILE *_fInt = fopen("ints", "r");
FILE *_fString = fopen("strings", "r");
readFile(_fInt, _vInt);
readFile(_fString, _vString);
for (int i = 0; i < 15; i++)
{
printf("%d %s\n", _vInt[i], _vString[i]);
}
fclose(_fInt);
fclose(_fString);
return 0;
}
I'm not sure if this is a really great example - it is certainly more complex than your two-loop solution, but I think it suits your requirements.
source to share