Hi all.
I am trying to write a program that can combine video files. Can someone please explain why the number of characters written is not equal to the number of characters read? I am getting the "File combine error" message.
Thanks in advance.
Code:
// joinvideofiles.c: combines video files by appending them
// 2 functions: openfile(), combine()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FILENAMELENGTH 40
#define BUFFERLENGTH 4096
FILE *fp1, *fp2;
int openfile(const char *file1, const char *file2);
void combine(const char *file1, const char *file2);
int main(void)
{
int x; // return value of openfile()
char file1[FILENAMELENGTH], file2[FILENAMELENGTH];
do
{
printf("Enter file 1: ");
fgets(file1, FILENAMELENGTH, stdin);
printf("Enter file 2: ");
fgets(file2, FILENAMELENGTH, stdin);
file1[strlen(file1) - 1] = '\0'; // known filenames, no overflow problems
file2[strlen(file2) - 1] = '\0'; // known filenames, no overflow problems
} while((x = openfile(file1, file2)) == 1);
combine(file1, file2);
return 0;
}
int openfile(const char *file1, const char *file2)
{
if(((fp1 = fopen(file1, "ab")) == NULL) || ((fp2 = fopen(file2, "rb")) == NULL))
{
fprintf(stderr, "Error opening file.\n");
return 1;
}
return 0;
}
void combine(const char *file1, const char *file2)
{
char buffer[BUFFERLENGTH];
size_t x; // number of characters read by fread()
while((x = fread(buffer, 1, BUFFERLENGTH, fp2)) > 0) // read file2 into buffer
{
if((fwrite(buffer, 1, BUFFERLENGTH, fp1)) != x) // write buffer to file 1
{
fprintf(stderr, "File combine error.\n");
exit(EXIT_FAILURE);
}
}
fclose(fp1);
fclose(fp2);
}