File I/O: Writing X to Y Bytes in a file
In the number "123456789", what if you wanted to replace the 5 with a 0 ("123406789")? Using simple file i/o writing functions, we can easily do this.
1) Assign your file a variable:
In this function, we declare a file with the name "example".
2) Open the file you assigned the "example" variable to.
example = fopen("./example.txt","r+b");
Also, note that there is a "r+b". Here are some simple definitions:
"r"- open a file for reading only
"w"- open a file for writing only
"b"- open a file in binary mode
"rb"- open a file for reading only in binary mode
"wb"- open a file for writing only in binary mode
"r+b"- open a file for reading and writing in binary mode
Note: If you don't use "r+b" in this case, and you use "wb" instead, then you can not read the bytes from X to Y (you must read the file for writing X to Y bytes; hard to learn at first).
3) After opening your file, add this line:
fseek(example, 4, SEEK_SET);
- "Reposition stream's position indicator." This requires 3 parameters, the pointer to an open file, the offset (how many bytes from the origin) and the origin." from psp-programming
goes to the beginning of the file.
The "4" goes, literally, four characters right from the beginning of the file. After adding this line, you can edit the next character, in this case, being "5".
4) Now, this code (fprintf) lets you write a character to the example variable we indicated earlier:
Note: the "0" is the character that we want to write in place of the 5. Any number or letters that you want can be replaced by the zero to write to the file (of course, it would be writing to the file after the fourth character that we "fseek"ed earlier).
5) Close the file before continuing the program:
I hope this helps. ;)