I'm working on a project for university, the basic idea is that I want to check if a file is empty.
void main() {
FILE* file = fopen("stocksData.csv", "w+");
fseek(file, 0, SEEK_END);
unsigned long len = (unsigned long)ftell(file);
if (len == 0) { //check if the file is empty
fclose(file);
importCarStock();
}
}
If it is empty, I want it to call this function:
void importCarStock() {
FILE* file = fopen("stocksData.csv", "w");
fwrite(carStock, sizeof(char), sizeof(carStock), file);
fclose(file);
}
And write this array to the file:
int carStock[10] = { 5, 7, 10 };
But the only thing it writes to the file is two small blocks. Any idea what is wrong with this? Thanks in advance.
1 Answer 1
fwrite(carStock, sizeof(char), sizeof(carStock), file);
This is the problem. fwrite writes binary data. If you have the array { 5, 7, 10 }, then it will write the bytes 05 00 00 00 07 00 00 00 0A 00 00 00 (assuming a little-endian system). You are seeing 2 blocks because of the bytes 05 and 07, which are control characters (the 0s are null characters and 0A is a line feed).
You need a for loop:
for (int i = 0; i < sizeof carStock / sizeof carStock[0]; i++)
fprintf(file, "%d ", carStock[i]);
If you want to output numbers to a file, you need to decide whether you want to see these numbers with a text editor or a hex editor. If you store them as text, it's easier to see them with a text editor like Notepad, but reading and writing costs more time and is more error-prone if string to number (and vice versa) conversions are not performed correctly. If you store them in binary, you won't be able to see them with a text editor, you will just see gibberish because your text editor tries to interpret binary data as ASCII/Unicode characters, however they take less space and are faster and easier to read and write.
Here are the bytes of the file generated with the for loop (you can check them with a hex editor):
35 20 37 20 31 30 20
And here are the bytes interpreted as text:
5 7 10
2 Comments
for loop I wrote writes the entire array. If you want only some of the values (like 3, in your example), you will need to keep track of this number in another variable and replace it in the for loop.
w+mode will empty it. Usermode.5, 7, 10are ASCII codes of something that might look like "two small blocks" in a text viewer.sprintf()orfprintf().