0

samplegame.txt(actual_file)

6
2 3 3
11 2
18 1
10 3
22 14
30 19
8 16
12 24
20 33

i want to read data .txt file into my C program.for each line separate them and store them in the variable,so i can use in further step.i'm trying to use

 FILE* file = fopen (argv[1], "r");
  int i = 0;

  fscanf (file, "%d", &i);
  while (!feof (file))
    {
      //printf ("%d ", i);
      fscanf (file, "%d", &i);
    }
  fclose (file);

but i got all the number in one line and can't figure out how to separate each group like

int board_size = 6  << 1st line 

int minion_box_size = 2; << 2nd line
int trap_size = 3;
int trampoline_size = 3;

int minion_box[minion_box_size] = {11,18}; << 3rd to N line 
int minion_walk[minion_box_size] = {2,1};

int trap_position[trap_size] = {10,22,30}; << N+1 to M line 
int trap_end[minion_box_size] = {3,14,19};

int trampoline_position[trampoline_size] = {8,12,20}; << M+1 to k line
int trampoline_jump[trampoline_size] = {16,24,33};

Anyone has a suggestion ?

samplegame.txt(explained)

______Board_________

6       //  size of game board 
_____size of each item_________
2 3 3      //  first number in this line is Minion_box,which means there is 2 Minion_box
           //  Second number is trap_holes,which means there is 3 traps
           //  third number is trampoline,which means there is 3 trampolines
_____Minion_Box_______
//  first number     : where the minion_box are 
//  Second number    : how many step that the minion can walk 
11 2       //  the box is in 11th block , minion has aiblity to walk 2 step
18 1       //  the box is in 18th block , minion has ability to walk 1 step
______Traps__________
//  first number     : where the traps are  
//  Second number    : the block you gonna be,after stepping on the trap.
10 3       // there is a trap hole in the 10th block,step on it and you will fall down 3rd block
22 14      // a trap hole in the 22th block,fall down to 14th block
30 19      // a trap hole in the 30th block,fall down to 19th block
____trampoline_______
//  first number     : where the trampoline are
//  Second number    : the block you gonna be,after stepping on the trampoline.
8 16       // there is a trampoline in 8th block,if you step on it you will jump to 16th block
12 24      // trampoline in 12th block,jump to 24th block
20 33      // trampoline in 20th block,jump to 33th block

Sorry for bad english and really long post,since i'm not good in english so i'm trying to show the example as much as possible :(

1 Answers1

0

If you want to read a file line after line, better use fgets() and sscanf().

char buffer[BUFFER_SIZE]; // with a #define BUFFER_SIZE 1024 or whatever sooner in the code
int first_value, second_value;

if (fgets(buffer, BUFFER_SIZE, f) == NULL)
{
    if ferror(f)
    {
        perror("");
    }

    exit(1);
}

if (sscanf(buffer, "%d %d", &first_value, &second_value) != 2)
{
    fprintf(stderr, "missing value\n");
    exit(1);
}
jdarthenay
  • 3,062
  • 1
  • 15
  • 20