I am trying to read a file, read in how many bytes it contains and then round it up to its nearest GB and then double the file size. However, is there is way to read the file and then some do all this stuff back into the same file?
Here is what I have so far, but it creates a new file with the new contents but I'm not sure if my logic is correct
Also, do you create a constant like BYTE with #define?
So far as a test case I just used byte as an int and make it equal to 50
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <time.h>
// #define BYTE 50
int main()
{
FILE *fp1, *fp2;
int ch1;
clock_t elapsed;
char fname1[40], fname2[40];
char a;
printf("Enter name of the file:");
fgets(fname1, 40, stdin);
while ( fname1[strlen(fname1) - 1] == '\n')
{
fname1[strlen(fname1) -1] = '\0';
}
fp1 = fopen(fname1, "r");
if ( fp1 == NULL )
{
printf("Cannot open %s for reading\n", fname1 );
exit(1);
}
printf("This program will round up the current file into highest GB, and then double it");
elapsed = clock(); // get starting time
ch1 = getc(fp1); // read a value from each file
int num = 50;
int bytes = 0;
while(1) // keep reading while values are equal or not equal; only end if it reaches the end of one of the files
{
ch1 = getc(fp1);
bytes++;
if (ch1 == EOF) // if either file reaches the end, then its over!
{
break; // if either value is EOF
}
}
// 1,000,000,000 bytes in a GB
int nextInt = bytes%num;
// example: 2.0GB 2,000,000,000 - 1.3GB 1,300,000,000 = 7,000,000,000 OR same thing as 2,000,000,000%1,300,000,000 = 700,000,000
int counter = 0;
printf("Enter name of the file you would like to create:");
fgets(fname2, 40, stdin);
while ( fname2[strlen(fname2) - 1] == '\n')
{
fname2[strlen(fname2) -1] = '\0';
}
fp2 = fopen(fname2, "w");
if ( fp1 == NULL )
{
printf("Cannot open %s for reading\n", fname2);
exit(1);
}
if(fp2 == NULL)
{
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
while(counter != nextInt)
{
a = fgetc(fp1);
fputc(a, fp2);
counter++;
}
fclose(fp1); // close files
fclose(fp2);
printf("Total number of bytes in the file %u: ", bytes);
printf("Round up the next GB %d: ", nextInt);
elapsed = clock() - elapsed; // elapsed time
printf("That took %.4f seconds\n", (float)elapsed/CLOCKS_PER_SEC);
return 0;
}