简体   繁体   English

如何在字符串表中保存文件的行?

[英]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? 我在C中有一个项目,告诉我读取文件并将每一行保存在字符串表stateTable [10] [50]中,我不知道该怎么做,有人可以帮助我吗? 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? 虽然我不知道通过将stateTable [i]放入gets是否正确,如果可以,保存在stateTable [10] [50]中的每个字符串的末尾都将带有\\ 0吗?

 #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. 从最后的printf语句可以看出,该代码有效。

The strlen shows that the \\0 is inserted. strlen显示\\ 0已插入。

Mind that the fgets retains the linefeed in the string. 请注意,fgets将换行符保留在字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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