I have a .dat file with two columns, time & channel of audio data. I am trying to just read the column channel, write it in a different .dat file and save it.
In the code, I have stored the file in a buffer and I'm able to read the values in the column. Now I'm trying to put the second column in another file named out.dat, but it looks like it's not writing anything into the file. Here's what I've done.
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;
}
First, you can copy the data into the new file and count the numbers with:
int counter = 0;
while (fgets(buffer, bufferLength, fp)) {
if (2 == sscanf(buffer, "%lf %lf", &a, &b)) {
counter += 1;
fprintf(outfp, "%f\n", b);
}
}
Then create an array and read the file again:
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??
}
}
Alternatively, you can combine these 2 loops and use realloc
to allocate memory for the array as you go:
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);
}
}