【问题标题】:Loop through data stored in buffer in C循环遍历存储在 C 中缓冲区中的数据
【发布时间】:2021-11-05 14:22:37
【问题描述】:

我有一个 .dat 文件,其中包含两列音频数据的时间和通道。我正在尝试仅读取列通道,将其写入不同的 .dat 文件并保存。

在代码中,我将文件存储在缓冲区中,并且能够读取列中的值。现在我试图将第二列放在另一个名为 out.dat 的文件中,但看起来它没有向文件中写入任何内容。这就是我所做的。

int main(){

double a=0;
double b=0;
int bufferLength = 330750;
char buffer[bufferLength];

FILE *fp = fopen("original.dat", "r");
if (!fp){
    printf("Cant open file\n");
    return -1;
}

FILE *outfp= fopen("out.dat", "w");
if(outfp == NULL)
{
    printf("Unable to create file\n");
}


while(fgets(buffer, bufferLength, fp)) {  
    if (2==sscanf(buffer, "%lf %lf", &a,&b)){  // Just printing col 2 //
        printf("b: %f\n", b);
    }
}
for(bufferLength=0; bufferLength<330750; bufferLength++){
    fputs(&bufferLength, outfp);
}

printf("File transferred\n");
fclose(outfp);
fclose(fp);
return 0;

}

【问题讨论】:

  • printf("b: %f\n", b); 在此处写入输出文件。 fprintf(outfp, "%f\n", b);
  • 我相信我现在可以看到 out.dat 文件中的数据了。非常感谢!
  • @JohnnyMopp 嗨,Johny,我现在正尝试将存储在文件指针中的值放入一个数组中。例如,我尝试了 printf("%f", outfp);打印 out.dat 中的浮点值并将其放入数组中。但是输出是错误的。您对如何将文件指针中的值放入数组有任何想法吗?

标签: c audio wav file-pointer


【解决方案1】:

首先,您可以将数据复制到新文件中并计算数字:

int counter = 0;
while (fgets(buffer, bufferLength, fp)) {  
    if (2 == sscanf(buffer, "%lf %lf", &a, &b)) {
        counter += 1;
        fprintf(outfp, "%f\n", b);
    }
}

然后创建一个数组并再次读取文件:

double *data = malloc(sizeof(*data) * counter);
if (!data) { /* handle error */ }
rewind(fp);  // If rewind is not available use fseek(fp, 0, SEEK_SET)
int index = 0;
while (fgets(buffer, bufferLength, fp)) {  
    if (2 == sscanf(buffer, "%lf %lf", &a, &b)) {
        data[index++] = b;  // Just saving b??
    }
}

或者,您可以组合这两个循环并使用realloc 为数组分配内存:

double *data = NULL;  // Important: needs to be initialized to NULL
int counter = 0;
while (fgets(buffer, bufferLength, fp)) {  
    if (2 == sscanf(buffer, "%lf %lf", &a, &b)) {
        double *temp = realloc(data, sizeof(*data) * (counter + 1));
        if (!temp) { /* handle error.... */ }
        data = temp;
        data[counter++] = b;
        fprintf(outfp, "%f\n", b);
    }
}

【讨论】:

  • 嗨,Johny,我尝试了前两个代码来计算数字并创建一个数组。他们都工作了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多