1

我制作了一个程序来处理和存储图书馆中的电影记录。这就是我将库打印到文件时的样子。所以基本上我的问题是读取这个文件并将这些列保存在我的变量结构中,并为每个条目动态增加结构的大小。现在我有一个while循环逐行读取缓冲区,然后我试图扫描缓冲区中的值。如果有帮助,我知道列之间间距的格式。(不,它不是制表符,这有帮助吗?)否则我想一旦它找到“两个空格”,它就可以解析到下一个……我是什么我正在寻找的是这样的:

("%s %d %d %d %s %d", 名称, &id, &qty, &price, 流派, &year)

这是文本文件的样子:“test.txt”(下面的更新版本)

-------------------------------------------------------------------------------
NAME                                          ID    QTY   PRICE GENRE      YEAR
-------------------------------------------------------------------------------
THE SHAWSHANK REDEMPTION                      1     25    99    Crime      1994
THE GODFATHER                                 2     65    199   Crime      1972
PULP FICTION                                  3     265   99    Drama      1994
THE LORD OF THE RINGS                         4     1024  199   Action     2003
THE DARK KNIGHT                               5     99    99    Action     2008

这就是我的代码的样子:

void read_from_file(struct movies *movie)
{
    FILE *fp;
    char buffer[1024];
    int line_num = 0;
    int index = 0;

    fp = fopen("test.txt", "r");

    if ( fp == NULL )
    {
        printf("Error opening file!\n");
        exit(1);
    }

    fgets(buffer, 1024, fp); fgets(buffer, 1024, fp); fgets(buffer, 1024, fp); // Skip 3 first lines (header)

    while(fgets(buffer, 1024, fp) != NULL) // read one line to buffer at a time
    {  
        printf("%s", buffer); //DEBUG 

        // Trying here to read only the names which i know should be no longer than 40chars. first row goes well, then it's messed up
        sscanf(buffer, "%40[^\0]" , movie[index].name);

        index++;
    }

    fclose(fp);
    getch();
}

更新:我将存储文件的格式更改为以下内容:

THE SHAWSHANK REDEMPTION,1,25,99,Crime,1994
THE GODFATHER,2,75,199,Crime,1972
PULP FICTION,3,512,99,Drama,2000
THE LORD OF THE RINGS,4,1024,199,Action,2003
THE DARK KNIGHT,5,99,99,Action,2008
4

1 回答 1

0

主要问题是没有单个字符分隔符。所以处理前 45 个字符;

while(fgets(buffer, sizeof buffer, fp) != NULL) {
  printf("%s", buffer); //DEBUG
  if (strlen(buf < 80)) {
    handle_short_line_error();
  }
  size_t len;
  for (len = 45; len > 0; len--) {
    if (!isspace(buf[len-1])) {
      break;
    }
  }
  if (!IsAGoodLength(len)) {
    handle_format_error();
  }
  memcpy(movie[index].name, buf, len);
  movie[index].name[len] = '\0';
  if (5 != sscanf(&buffer[45], "%d%d%d%9s%d", &id, &qty, &price, genre, &year)) {
    handle_format_error();
  }
  // Use other fields scanned
  index++;
} 
于 2013-10-21T23:18:06.770 回答