简体   繁体   中英

How to save a file's lines in a string table?

i have project in C that tells me to read a file and save each line in a string table stateTable[10][50],and i dont know how to do it,can anyone help me? All i have come up with for now is:

int i=0,j=0,x=10,y=50;
char stateTable [ 10 ][ 50 ];
static const char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
    while ( fgets ( stateTable[i], y , file ) != NULL )
    {
        i++;
    }
    fclose ( file );
}
else
{
    perror ( filename );
}
return 0;

Although i dont know if by putting stateTable[i] in gets is correct,and if so will each string which is saved in the stateTable[10][50] have \\0 at the end?

 #include <stdio.h>
 #include <string.h>
 int main(void)
 {
   int j, i = 0;
   const int y = 50, x= 10;
   char stateTable [ x][ y ];
   const char filename[] = "file.txt";
   FILE *file = fopen ( filename, "r" );
   if ( file != NULL )
   {
   while ( fgets ( stateTable[i], y , file ) != NULL )
  {
    i++;
    if (i >  x)
    break;
  }
  fclose ( file );
}
else
{
perror ( filename );
}
for  (j=0 ; j < i; j++)
{ 
  printf ( "\nstateTable[j] %s len = %zu",
       stateTable[j], strlen (stateTable[j]));
 }
printf ("\n");
return 0;
}

As seen from the printf statement in the end it shows that the code works.

The strlen shows that the \\0 is inserted.

Mind that the fgets retains the linefeed in the string.

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