Cory
Cory

Reputation: 245

fscanf inside a loop

Ah, thanks! Makes sense. Just made command of size MAX_COMMAND_LENGTH + 1.

I am trying to to use fscanf to read the same file 2 different times in a loop but I am getting a seg fault. The idea is that the file will be formatted so that it has a command at the beginning of each line, followed by arguments for the command.

  char* command;  //Changed to char command[MAX_COMMAND_LENGTH + 1]

  while(fscanf(file, "%s", command) == 1)
  {
    if (strcmp("CMD1", command) == 0)
    {    
      int index, exp, coeff;
      fscanf(file, "%d %d %d", &index, &exp, &coeff);
    }
    else if (strcmp("CMD2", command) == 0)
    {
      int num;
      fscanf(file, "%d", &num);
    }
}

Upvotes: 0

Views: 1299

Answers (4)

MByD
MByD

Reputation: 137282

You should allocate a buffer to read the command. Currently command is not initialized and it points to sum invalid address. So either you "malloc()" memory for command or declare command as an array (char command[whateversizeyouneed])

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490048

Right now you just have a pointer. You need to allocate some space to hold the string you read:

char command[256];

if (fscanf(file "%256s", command)==1)
    // ...

Upvotes: 0

bmargulies
bmargulies

Reputation: 100013

You need to allocate some storage and store it in 'command'. You are asking fscanf to write through an uninitialized pointer.

Upvotes: 0

srgerg
srgerg

Reputation: 19329

You need to allocate memory for command. For example:

command = (char *)malloc(1024 * sizeof(char));

will allocate enough memory for 1024 characters.

Remember to free(command) when you're finished with it.

Upvotes: 3

Related Questions