如果每行都以换行符结束,则在C中读取文件

时间:2018-01-13 13:33:10

标签: c file

显然我在阅读文件,逐行或逐个字符时遇到一些问题,因为我的文件的每一行都是由换行符终止的。 我认为这个问题与那些新行字符有关,因为当我尝试读取文件时,使用或者fgetc()或fgets(),当我尝试在stdout上打印结果时,我给了......没什么。

第一个给我这个问题的文件示例:

12345678
12849499
47484900

我尝试使用其他文件,例如

123456596945869498

stdout上的输出,使用fgetc()或fgets()解析文件,是我所期望的:文件的内容。

现在,从文件读取的目的是将文件的内容存储在指针的矩阵中。我试图以多种方式绕过这些换行符。我试过这样:

i = 0;
while((c = fgetc(f)) != EOF){
    if(c != '\n')
       p[i][j++] = c; /*Incrementing j by one ad each iteration */
    if(c == '\n')
        i++; /*If c == '\n', skip to the next row of the matrix */
    }

其中I是行索引,j是列索引。 我甚至尝试过像这样的fgets,正如这个论坛的成员所建议的那样:

while((fgets(line, col,f))!= NULL){
        p[i++] = strdup(line);
        }

有人可以帮我弄清楚如何解决这个问题吗?

这是我的计划的主要内容:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define K 100

int main() {
  FILE *f;

  f = fopen("out_test6_1.txt", "r");

  int row = 0;
  int col = 0;
  char c;

  // Evaluating number of rows and columns of the new matrix, 
  // parsing the file in search of newlines chars

  while((c = fgetc(f)) != EOF ) {
    if(c != '\n' && row == 0)
    col++;

    else if(c == '\n')
    row++;
  }

  printf("rows %d\n", row);
  printf("columns %d\n", col);

  int i, j;
  char**p = malloc(row*sizeof(char*));
  for(i = 0; i < row; i++) {
    p[i] = malloc(col*sizeof(char));
  }

  i = 0;
  while((c = fgetc(f)) != EOF) {
    if(c != '\n')
    p[i][j++] = c;
    if(c == '\n')
    i++;
  }

  for(i = 0; i < row; i++) {
    for(j = 0; j < col; j++) {
      printf("%c", p[i][j]);
    }
  }

  fclose(f);

  return 0;
}

1 个答案:

答案 0 :(得分:0)

代码读取文件以查找行和列,但在第二遍之前无法倒回。

i = 0;
rewind(f);  // add
while((c = fgetc(f)) != EOF) {

注意到其他一些问题:

// To properly distinguish all characters from EOF
// char c;
int c;

我希望代码可以找到最大列宽并稍后再使用。

  size_t max_col = 0;
  while((c = fgetc(f)) != EOF ) {
    col++;
    if (c == '\n') {
      if (col > max_col) {
        max_col = col;
        col = 0;
      }
      row++;
    }
  }
  if (col > max_col) {
    max_col = col;
  }

  ... 
  // p[i] = malloc(col*sizeof(char));
  p[i] = malloc(sizeof *(p[i]) * max_col);