Reputation: 5
Reads the file and multiplies the data by 2. After that, I wrote a program that writes to another file. This file is a 16-bit file. By the way, only a certain number is written to the created file. I do not know why this is happening. Please help me.
C (visual studio 2017)
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 16000
typedef short data_type;
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
FILE *fd, *fd2;
data_type *data;
int n;
data = (data_type*)malloc(sizeof(data_type) * SIZE);
for (int i = 0; i < SIZE; i++)
data[i] = 0;
if ((fd = fopen("C:\\Users\\SeoHyeon\\Documents\\test16kSam16bMono.pcm", "r")) == NULL)
printf("Error opening file1");
if ((fd2 = fopen("C:\\Users\\SeoHyeon\\Documents\\test16kSam16bMono2.pcm", "w")) == NULL)
printf("Error opening file2");
n = fread(data, sizeof(data_type), SIZE, fd);
for (int i = 0; i < SIZE; i++)
data[i] = data[i] * 2.0;
if (fwrite(data, sizeof(data_type), SIZE, fd2) != SIZE) {
printf("Error writing to file.\n");
exit(1);
}
fclose(fd);
fclose(fd2);
free(data);
return 0;
}
Upvotes: 0
Views: 2500
Reputation: 14906
It could be that the program is not opening both the files in binary mode.
For example:
FILE *fin = fopen("input_file.bin", "rb"); // <-- Note the "rb"
If your file is opened in text mode, which is the default, if there's an EOF character in the data, the file-input could close prematurely.
EDIT: Also, you should handle the error when your file-handles fd
and fd2
are NULL. There's also a couple of other error conditions you aren't checking for, but I leave these as an exercise for the reader.
Upvotes: 1