-2

If i got the following file

1 station1 1
2 station2 2
3 station3 3
4 station4 4
5 station5 5
6 station6 6
7 station7 7
8 station8 8
9 station9 9
10 station10 10

and i want to read the data of the first and last line. I tried this:

    for (i=0; i<n; i++) {
    ret = fork();
    if (ret == 0) {
                fscanf(fstation,"%d %s %d",id, station, num);
                printf("Identifier is %d %s %d \n",id,station,num);


                exit(0);


        }else{wait(&st);}



        }

And the output is this.

Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0
Identifier is 0   0

It doesen't works very well, what im doing wrong? EDIT: sorry for the misunderstanding, i tried to translate part of the code to make it more understandable.

MarcoGarzini
  • 82
  • 10
  • 2
    fscanf should be given pointers to id, station and num (i.e. &id, &ststion,&num). Btw, why do you fork? – Harald Nov 22 '15 at 21:51
  • Same result with pointers, I use fork cause i work with child process for each line. – MarcoGarzini Nov 22 '15 at 21:54
  • 2
    Can you show us the new code? Btw, the output does not match the printf. – Harald Nov 22 '15 at 21:57
  • 1
    Please post an [Minimal Complete and Verifiable Example](https://stackoverflow.com/help/mcve). As it is, your code and description don't correlate properly. So it is difficult to say whether certain things are real bugs in your code or just typos. For example, the `fscanf` implies that `station` stores a string. Yet the `printf` prints it as an int. So which is right/wrong? You have not even shown the definition of `station` or any of the other variables. – kaylum Nov 22 '15 at 22:04

2 Answers2

0

Everything that's scanned in from fscanf needs to be dereferenced.

fscanf(fstation,"%d %s %d",id, station, num);

In this case you have "id" and "num" in fscanf as normal variables, and it will treat the value stored in the variables as the addresses in which to send the new information. In order to store the new information in the variables you want, you need to give fscanf the addresses to those variables. This can be done with the ampersand(&).

fscanf(fstation,"%d %s %d", &id, station, &num);

Strings, however, don't have to be done this way as they are already pointers to addresses (an array of characters). so in this case, 'station' can be left without an ampersand.

DreamCloud
  • 113
  • 1
  • 9
0

This other question/answers on stackoverflow seems related. The answers nidicate that you need to fopen() file after fork() both for parent and child separately

writing and reading within a fork - C

Community
  • 1
  • 1
Harald
  • 3,110
  • 1
  • 24
  • 35