【问题标题】:Reading from file into Structure in C从文件读取到C中的结构
【发布时间】:2016-04-05 08:23:26
【问题描述】:

我是 C 编程新手,在播放音符的 MIDI 录音程序上做一些工作,但似乎无法让程序从文件中读取到我的结构数组中。

结构如下:

typedef struct
{
    int noteNumber;
    int vel;
    int oscillatorNumber;
    float freq;
} oneNote;

这里是阅读注释的代码:

oneNote notes[2000];

for (count = 0; count < fileSize; count++)
{
    fscanf(filePointer, "%d %d %d\n", &notes[count].noteNumber,
                                      &notes[count].vel,
                                      &notes[count].oscillatorNumber);

    notes[count].freq = ntof(notes[count].noteNumber);
}

文件打开的代码:

filePointer = fopen("noteRecordFile.txt", "r");

if (filePointer == NULL)
{
    printf("Error opening file\n");
}
else
{
    printf("File opened\n");

    fseek(filePointer, 0L, SEEK_END);
    fileSize = ftell(filePointer);
}

只是不存储结构中的数据和,如下所示:

Image of debug console

noteRecordFile.txt 的前几行:

48 108 0
50 108 0
52 100 0

【问题讨论】:

  • 请提供您打开文件的代码部分
  • 我现在已经完成了,当我运行程序时它说文件已打开
  • 请提供noteRecordFile.txt文件的前几行。
  • 我已将其编辑到帖子中
  • 在确定文件长度的过程中,您已经到达文件末尾。您是否忘记使用fseek(filePointer, 0L, SEEK_SET) 回到文件开头?

标签: c midi audio-player


【解决方案1】:

有几个问题:

删除以下 2 行,因为它将文件指针放在文件末尾,我们想从文件开头开始读取,ftell 会给你文件中的字节数,而不是行数。

fseek(filePointer, 0L, SEEK_END);
fileSize = ftell(filePointer);

那么你需要这个:

  FILE *filePointer = fopen("noteRecordFile.txt", "r");

  if (filePointer == NULL)
  {
      printf("Error opening file\n");
      exit(1);   // <<< abort program if file could not be opened
  }
  else
  {
      printf("File opened\n");
  }

  int count = 0;
  do
  {
      fscanf(filePointer, "%d %d %d", &notes[count].noteNumber,
                                        &notes[count].vel,
                                        &notes[count].oscillatorNumber);

      notes[count].freq = ntof(notes[count].noteNumber);
      count++;
  }
  while (!feof(filePointer));  // <<< read until end of file is reached
  ...

如果不读取整个文件,我们无法知道文件包含的行数,因此我们使用不同的方法:我们只读取直到到达文件末尾。

你还是需要加个检查,因为如果文件包含超过2000行,你会遇到麻烦。这留给读者作为练习。

【讨论】:

    【解决方案2】:

    不会因为你到达了文件的末尾就行了:

    fseek(filePointer, 0L, SEEK_END);
    

    您需要将文件指针重置为文件的开头:

    fseek(filePointer, 0L, SEEK_SET)
    

    【讨论】:

    • 谢谢,原来是这个问题
    • @HarryJordan:这只是一个的问题。阅读我的答案。
    【解决方案3】:

    您确定您的文件格式吗? 如我所见,您也将标题作为普通数据线阅读...

    尝试阅读本文,也许它会对你有所帮助。

    MIDI

    您可以尝试将文件作为二进制文件打开,我记得它修复了我在某些声音文件上遇到的问题...!

    您在编译和执行过程中是否有任何错误/警告?

    【讨论】:

    • 文件格式很好,sjsam 有答案,但是谢谢
    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2015-04-06
    • 2011-05-08
    • 1970-01-01
    相关资源
    最近更新 更多