I am trying to make a program that generates a string given user input, and then passes that string to a function that will change stdin to a dummy file, write the string to the file, use scanf on said file, then delete the file, but I'm having trouble redirecting stdin to the dummy file, any help on the best action that will only extend into the scope of the function?
int scan(const char* __restrict__ _format, ...){
FILE* original = stdin, *mod = calloc(1, sizeof(FILE));
mod = freopen("testFile.txt", "w+", stdin);
fputs(_format, stdin);
int a, b;
scanf("%d %d", &a, &b);
printf("%d, %d", a, b);
// freopen(orig)
return 1;
}
void swap(char* a, char* b) {
if (*a != ' ' && *b != ' ') {
char temp = *a;
*a = *b;
*b = temp;
}
}
void permiate(char* str, int start, int end){
int i;
if(start == end){
printf("%s\n", str);
}else{
for(i = start; i<=end; i++){
swap(str+start, str + i);
permiate(str, start + 1, end);
swap(str + start, str + i);
}
}
}
int main(){
int a, b;
char str[] = "1 3";
//function to put string to stdio
scan(str);
scanf("%d %d", &a, &b);
printf("%d, %d", a, b);
return 0;
}
after someone pointed out fscanf, a function i was never aware of becasue my teacher never covered it, i have found a working solution to the scan function:
int scan(const char* __restrict__ _format, ...){
int *a = malloc(sizeof(int)), i = 0;
FILE *fp1 = fopen("testfile.txt", "w");
fputs(_format, fp1);
freopen("testFile.txt", "r", fp1);
while(fscanf(fp1, "%d", &a[i]) != EOF){
i++;
a = realloc(a, sizeof(int)*i);
}
for(int j = 0; j < i; j++){
printf("%d, ", a[j]);
}
fclose(fp1);
return 1;
}
but whenever i give str a value like "1 2 3 4 5 6 ..." or anything that has more than 5 numbers, the 5th number is always 0 if i leave realloc in, if i comment that line out, then it is fine. any idea on what that is about? ps my labs at uni only got to basic uses of arrays, no dynamic memory or anything, so if im using anything wrong it would b greatly appriciated