How to read a string using freopen

Hello! I have to read a string from a file using the freopen function but it doesn't work. This is the code:
1
2
3
4
5
6
7
8
9
10
#include<stdio.h>

int main()
{   char x[100];
    freopen("bitcell.in", "r", stdin);
    freopen("bitcell.out", "w", stdout);
    scanf("%s", &x);
    printf("%s", &x);
    return (0);
}

It simply doesn't print anything. Instead, I got 2 warnings:
1
2
3
4
D:\Projects in C-B-C++\bitcell project\main.c||In function 'main':|
D:\Projects in C-B-C++\bitcell project\main.c|7|warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[100]' [-Wformat]|
D:\Projects in C-B-C++\bitcell project\main.c|8|warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[100]' [-Wformat]|
||=== Build finished: 0 errors, 2 warnings ===|

Thanks!
&x evaluates to a pointer to an array which has type char (*)[100]. x would evaluate to a pointer to the contents of the array which would have type char*, which is a string. Although I don't know if this is the cause (the actual values of both pointers should be the same).

Does the bitcell.in file exist? What if you only did printf("foobar"); (with stdout reopened) ? You should probably close the files too.
Last edited on
Yes, that file exist. It has 4 lines o text in it. About what you said, I've noticed something:
If I build this code:
1
2
3
4
5
6
7
8
9
10
#include<stdio.h>

int main()
{   char x[100];
    freopen("bitcell.in", "r", stdin);
    freopen("bitcell.out", "w", stdout);
    scanf("%s", &x);
    printf("something");
    return (0);
}
it doesn't print the string "something". But if I build this code:
1
2
3
4
5
6
7
8
9
10
#include<stdio.h>

int main()
{   char x[100];
    freopen("bitcell.in", "r", stdin);
   // freopen("bitcell.out", "w", stdout);
    scanf("%s", &x);
    printf("something");
    return (0);
}
it prints the string "something". So if I open the stdout It doesn't print anything? What shall I do then?
If you don't reopen stdout, of course it will behave as normal. If you do, it should print the text in a file.
Again, 1. remove &, 2. close files after writing.
Topic archived. No new replies allowed.