简体   繁体   中英

How can I copy a specific string from an text file to an Array in C?

I have written this code and i don't know why it has the following two problems:

1)It copys strings from the text file in to the Odd parts of the Array (ex:lines[3] or lines[5] )

2)It doesn't copy all the file but stops whenever it wants and crashes in the end.

Please help me with this and if someone can tell me how to copy a specific string from an text file in C it would be much appreciated !

C CODE :

#include <stdio.h>

int height, length;

int main()
{

  int i;
  char **lines;
  FILE *tfile = fopen("this.txt", "r");

  if (tfile != NULL )
  {
    fscanf(tfile, "%d %d", &height, &length);
    printf("here:%d,%d\n", height, length);
    /*dynamic equasition of memory with malloc*/
    lines = (char **) malloc(sizeof(char *) * (height + 1));/*height + 1 ('\0')*/
    for (i = 0; i < 2 * height; i++)
    {
      lines[i] = (char *) malloc(sizeof(char) * (length + length + 1));/*height + height ('|') + 1 ('\0')*/
    }

    for (i = 0; i < (2 * height); i++)
    {
      fgets(lines[i], ((2 * length) + 1 + 1), tfile);/*length='spaces' + length+1='|' + 1='\0'*/
      if (i % 2 != 0)
      {
        printf("%s\n", lines[i]);
      }
    }
    fclose(tfile);
  }
  else
  {
    printf("Error: unable to open file.");
  }

  free(lines);
  return 0;
}

TEXT FILE (this.txt) :

http://www.csd.uoc.gr/~hy100/glid.txt

Every answer is much appreciated. IT

Lets analyze your code:

#include <stdio.h>
// you did not include <stdlib.h> needed for malloc, so to suppress the compiler 
// warning you have casted the return value of malloc, which is not needed.

int height, length; // no need to make these global as of now.

int main()
{

  int i;
  char **lines;
  FILE *tfile = fopen("this.txt", "r");

  if (tfile != NULL )
  {
    fscanf(tfile, "%d %d", &height, &length);
    printf("here:%d,%d\n", height, length);
    /*dynamic equasition of memory with malloc*/
    lines = (char **) malloc(sizeof(char *) * (height + 1));/*height + 1 ('\0')*/
// you only need height in above line, not height+1,
// '\0' is needed for sting, this is an array of strings.
// also casting is not needed.
    for (i = 0; i < 2 * height; i++) // You have allocated height+1, but trying to access 2*height, this invokes undefined behavior.
    {
      lines[i] = (char *) malloc(sizeof(char) * (length + length + 1));/*height + height ('|') + 1 ('\0')*/
// after examining the text file you provided, I think you need length +length +2
// length number of ' ' + length number of '|' + one more '|' + '\0' 
    }

    for (i = 0; i < (2 * height); i++)
    {
      fgets(lines[i], ((2 * length) + 1 + 1), tfile);/*length='spaces' + length+1='|' + 1='\0'*/
// You have allocated length + length+ 1, i.e. 2*length+1, but reading 2*length+2
// this will invoke undefined behavior.
      if (i % 2 != 0)
// this will print the odd line, as i%2!=0 is true when i is odd,
// I think this is desirable as in your file even lines only have '\n'
      {
        printf("%s\n", lines[i]);
      }
    }
    fclose(tfile);
  }
  else
  {
    printf("Error: unable to open file.");
  }

  free(lines);
// This is not the proper way to free. You have to free in the same way you have allocated.
  return 0;
}

Here is my modification:

#include <stdio.h>
#include <stdlib.h> // for malloc

int main()
{

  int i;
  char **lines;
  int height, length; //local to main
  FILE *tfile = fopen("this.txt", "r");

  if (tfile != NULL )
  {
    fscanf(tfile, "%d %d", &height, &length);
    printf("here:%d,%d\n", height, length);
    /*dynamic equasition of memory with malloc*/
    lines = malloc(sizeof(char *) * (height)); // no need to cast the return value
    for (i = 0; i < height; i++)
    {
      lines[i] = malloc(sizeof(char) * (2*length + 2));/*height' '+height'|'+ 1'|'+1'\0'*/
    }

    for (i = 0; i < height; i++)
    {
      fgets(lines[i], 2*length+2, tfile);/*height' '+height'|'+ 1'|'+1'\0'*/
      if (i % 2 != 0)
      {
        printf("%s\n", lines[i]);
      }
    }
    fclose(tfile);
  }
  else
  {
    printf("Error: unable to open file.");
  }

    for (i = 0; i < height; i++)
    {
      free(lines[i]); // free all the strings
    }
  free(lines); // free the string array
  return 0;
}
#include <stdio.h>

int main()
{
   FILE *fp = NULL;
   int line = 0, readLineStart = 0, readLineStop = 0, startIndex = 0, endIndex = 0;
   char buffer[512], *cPtr = NULL;

   fp = fopen("file.txt", "r");
   if(fp == NULL)
   {
      return -1;
   }

   readLineStart = 3;
   readLineStop = 6;
   startIndex = 2;
   endIndex = 9; //must startIndex < endIndex
   while(fgets(buffer, 512, fp) != NULL)
   {
      line++;
      if(line >= readLineStart && line <= readLineStop)
      {
         printf("Line:%s", buffer);
         cPtr = buffer;
         *(cPtr + endIndex) = '\0';
         printf("Get:%s\n", cPtr + startIndex);
      }
   }
   fclose(fp);
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM