C simple file IO
I want to do a few tests to check my understanding of file IO, they are as follows:
1) create a file with exactly 404 bytes, no more, no less
I accomplish this by
Problem 1) Anytime fputc anything other than 1 or 0, my file size is no longer
/* creates a file of exactly 404 bytes, no more, no less */
int i; /* for iteration */
/* open file for writing */
FILE *file = fopen("file.txt", "w");
/* fill 404 bytes with 0 */
for (i = 0; i < 404; ++i)
fputc(rand() % 2, file);
/* close the file */
404. Can somebody explain this?
2) readfile -- read a file's first 4 bytes as an integer, followed by 100 10 by 10 grid of integers which are the next 400 bytes
I accomplish this by doing
Problem 2) I do not want to use fseek, but when i ignore it altogether, my ftell remains 0 somewhy, it really bothers me. Why is this happening?
/* reads 404 bytes from a file as INTEGERS */
int i, j;
FILE* file = fopen("file.txt", "r");
/* first DWORD */
fscanf(file, "%i", &tmp);
printf("%i:\t\t%i\n", ftell(file), tmp);
fseek(file, ftell(file) + 4, SEEK_CUR);
/* next 100 DWORDs */
for (i = 0; i < 10; ++i)
for (j = 0; j < 10; ++j)
fscanf(file, "%i", &tmp);
fseek(file, ftell(file) + 4, SEEK_SET);
printf("%i ", tmp);
Problem 3) The output of this program is 0 followed by 100 0s, the ftell is giving me the right numbers, but the values are not right! Can somebody explain this?
3) setbyte -- sets a particular dword in a file to a certain value, without changing the size of file, being 404 no more, no less
Problem 4) When I run readfile, nothing changes, so I do not even know if my
void SetByte(FILE* file)
/* skip to addr */
fseek(file, addr * 4, SEEK_SET);
/* set the value */
fwrite(&value, 4, 1, file);
FILE *file = fopen("file.txt", "w+");
printf("which dword to set? $ ");
printf("which value to set? $ ");
setbyte works or not because i know that readfile does not work, but I do
know that after I rune setbyte, the size of my file changes to 4 bytes!
This, i do not understand. Can somebody explain?
Irrelevant problem 5) Is it possible to set a value of a file to be negative, because from my understanding, end of file is marked as a negative value
(2s complement), but if I want to store negative numbers, I would assume
my file would just consider them to be the end of file... This makes working
with files in binary mode very frustrating for me. Can somebody explain if
my understanding is accurate or not, and if not explain the holes in my reasoning?
This is not an assignment, I am doing this because I am confused in using file io and I would like to combat this confusion with these tests. Sadly, this is not working out as smoothly as I expected, and I greatly appreciate all help I can get on this topic.
Thanks ahead of time