遍历存储在 C 缓冲区中的数据

Loop through data stored in buffer in C

我有一个包含两列的 .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;

}

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

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??
    }
}

或者,您可以组合这 2 个循环并使用 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);
    }
}