相关疑难解决方法(0)

在C中逐行读取文件

我正在尝试编写一些代码来打开文件,逐行读取其内容并将这些行存储到一个数组中.

首先,我打开文件并计算行数,每行都是固定长度,所以我只是这样做:

    char buf2[LINE_LENGTH];
    int in2 = open("toSend2", O_RDONLY);
    int number_of_lines = 0;

    for (;;)
 {
  char* p2 = buf2;
  int count = read (in2, p2, LINE_LENGTH);
  if (count < 0)
  {
    printf("ERROR");
    break;
  }
  if (count == 0) break; 

  number_of_lines++;

  printf("count: %d \n",count);
  printf("File 2 line : %s", p2);
  printf("\n");

 }
 close (in2);
Run Code Online (Sandbox Code Playgroud)

到目前为止,这很有效,number_of_lines确实是文件"toSend2"中的行数,而我的每个printf都是该文件中包含的行.

现在有了行数,我创建了一个字符串数组,然后我基本上再次遍历整个文件,但这一次,我想将每一行存储在数组中(可能有更好的方法来查找数字文件中的行,但我尝试的所有内容都失败了!)

    char * array[number_of_lines];
    int b=0;
    int in3=0;
    in3 = open("toSend2", O_RDONLY);
    for (;;)
 {
  char* p3 = buf3;
  int count = read (in2, p3, …
Run Code Online (Sandbox Code Playgroud)

c arrays storage file line

2
推荐指数
1
解决办法
2859
查看次数

如何在C中逐行读取文件?

我有一个文本文件,最多100个IP地址,每行1个.我需要将每个地址作为字符串读入名为"list"的数组中.首先,我假设"list"需要是一个二维char数组.每个IP地址长度为11个字符,如果包含"\ 0"则为12个,因此我声明列表如下:

char list[100][12];

接下来,我尝试使用fgets来读取流:

  for (i = 0; i < 100; i++)  
  {  
      if (feof(stream))  
          break;  
          for (j = 0; j < 12; j++)  
          fgets(&list[i][j], 12, stream);  
      count++;  
  }
Run Code Online (Sandbox Code Playgroud)

要检查字符串是否已正确读取,我尝试输出它们:

  for (i = 0; i < 5; i++)  
  {  
      for (j = 0; j < 11; j++)  
          printf("%c", list[i][j]);  
      printf("\n");  
  }
Run Code Online (Sandbox Code Playgroud)

运行程序后,很明显出错了.作为初学者,我不确定是什么,但我猜我正在读错文件.没有错误.它编译,但在两行打印一个奇怪的地址.

编辑:

我用这个替换了fgets代码:

for (i = 0; i < 100; i++)
  {
      if (feof(stream))
          break;
      fgets(list[i], 12, stream);
      count++;
  }
Run Code Online (Sandbox Code Playgroud)

它现在打印五个字符串,但它们是来自内存的"随机"字符.

c arrays file fgets

1
推荐指数
1
解决办法
5606
查看次数

标签 统计

arrays ×2

c ×2

file ×2

fgets ×1

line ×1

storage ×1