开发者

c++ File input/output

开发者 https://www.devze.com 2022-12-28 23:45 出处:网络
I am trying to read from a file using fgets and sscanf. In my file, I have characters on each line of the while which I wish to put into a vector. So far, I have the following:

I am trying to read from a file using fgets and sscanf. In my file, I have characters on each line of the while which I wish to put into a vector. So far, I have the following:

FILE *fp;
  fp = fopen(filename, "r");
  if(!fp)
  {
    fprintf(stderr, "Unable to open file %s\n", filename);
    return 0;
  }
  // Read file
  int line_count = 0;
  char buffer[1024];
  while(fgets(buffer, 1023, fp))
  {
    // Increment line counter
    line_count++;

    char *bufferp = buffer;

    ...

    while(*bufferp != '\n')
    {
      cha开发者_运维百科r *tmp;
      if(sscanf(bufferp, "%c", tmp) != 1)
      {
        fprintf(stderr, "Syntax error reading axiom on "
                "line %d in file %s\n", line_count, filename);
        return 0;
      }

      axiom.push_back(tmp);
      printf("put %s in axiom vector\n", axiom[axiom.size()-1]);

      // increment buffer pointer
      bufferp++;
    }
  }

my axiom vector is defined as vector<char *> axiom;. When I run my program, I get a seg fault. It happens when I do the sscanf. Any suggestions on what I'm doing wrong?


tmp is a pointer and not an array so reading into it results in a buffer overrun.

for a start you should change the decleration of tmp to:

  char *tmp = malloc(SOME_MAXIMUM_SIZE * sizeof(char));

and then you should remember to free all of the pointers in axioms when you're done.


A safer approach is to use std::string and std::vector<std::string>.

The string type handles memory allocation for your text. See also getline and std::string::c_str().

0

精彩评论

暂无评论...
验证码 换一张
取 消