Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
Thread: C simple file IO
11-10-2012, 11:56 PM #1
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
/* 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
/* 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
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