簡體   English   中英

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

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

我在C中有一個項目,告訴我讀取文件並將每一行保存在字符串表stateTable [10] [50]中,我不知道該怎么做,有人可以幫助我嗎? 我現在想出的是:

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;

雖然我不知道通過將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;
}

從最后的printf語句可以看出,該代碼有效。

strlen顯示\\ 0已插入。

請注意,fgets將換行符保留在字符串中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM