[C] [Solved ]Why " fwrite " writes werid number as binary ?
Posted: 2024-11-14 20:29
Hello Dears
I reversed the order of my code as :
And this is what I get :
Screenshot of GHex
I entered a 1.1 GB file and rt is 999,999 but fwrite writes it as 44 bytes I convert it to decimal both as littleendian and bigendian but there's no true number ....
Can Anyone Help ?
Thnaks
I reversed the order of my code as :
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <gmp.h>
int main(void)
{
FILE * fr, * fw;
char filename[201];
unsigned long int size = 0;
unsigned long int rt = 999999;
unsigned char ch[1] = {112};
printf("Enter filename : ");
fgets(filename, 200, stdin);
filename[strlen (filename) - 1] = '\0';
fr = fopen(filename, "rb+");
if (fr == NULL)
{
fprintf(stderr, "Error during opening of file %s\n", filename);
perror("");
return 1;
}
fseek(fr, 0L, SEEK_END);
size = ftell(fr);
fseek(fr, 0L, SEEK_SET);
if (size == -1)
{
fprintf(stderr, "Size doesn't match\n'");
perror("");
return 1;
}
if ( size > SIZE_MAX)
{
fprintf(stderr, "The size of file is greater than acceptable\n");
perror("");
return 1;
}
unsigned char * buf = NULL;
buf = malloc((size_t)size);
if(buf == NULL)
{
fprintf(stderr, "Buffer failure\n");
perror("");
return 1;
}
int r;
r = fread(buf, size, 1, fr);
printf("%d\n", r);
if (ferror(fr))
{
fprintf(stderr, "Error during reading from file %s\n", filename);
perror("");
fclose(fr);
return 1;
}
fclose(fr);
fr = NULL;
mpz_t x;
mpz_init(x);
mpz_t y;
mpz_init(y);
mpz_import(x, size, 1, (size_t)1u, 0, 0, buf);
mpz_root (y, x, rt);
int rootnum = 0;
unsigned long int num = rt;
do
{
num = num/10;
++rootnum;
}while(num != 0);
fw = fopen(filename, "wb+");
if(fw == NULL)
printf("File can't be written\n'");
if(ferror(fw))
{
fprintf(stderr, "Error during writing to file %s\n", filename);
perror("");
fclose(fw);
return 1;
}
int w;
w = fwrite(&rt, rootnum, 1, fw);
printf("%d\n", w);
fclose(fw);
fw = fopen(filename, "ab+");
if(fw == NULL)
printf("File can't be written\n'");
if(ferror(fw))
{
fprintf(stderr, "Error during writing to file %s\n", filename);
perror("");
fclose(fw);
return 1;
}
fwrite(ch, 1, 1, fw);
fclose(fw);
memset (buf, 0u, size);
mpz_export(buf, NULL, 1, (size_t)1u, 0, 0, y);
printf("\nEnter copied filename : ");
fgets(filename, 200, stdin);
filename[strlen (filename) - 1] = '\0';
fw = fopen(filename, "ab+");
if (fw == NULL) {
fprintf(stderr, "Error during opening of file %s\n", filename);
perror("");
return 1;
}
fwrite(buf, mpz_sizeinbase(y, 10), 1, fw);
if (ferror(fw)) {
fprintf(stderr, "Error during writing to file %s\n", filename);
perror("");
fclose(fw);
return 1;
}
fclose(fw);
free(buf);
mpz_clear(x);
mpz_clear(y);
return 0;
}
Screenshot of GHex
I entered a 1.1 GB file and rt is 999,999 but fwrite writes it as 44 bytes I convert it to decimal both as littleendian and bigendian but there's no true number ....
Can Anyone Help ?
Thnaks