Reputation: 21881
I am working on C/UNIX and have an input file having number of records. I have mapped each record to a structure and writing the structure to an output file by adding missing information in a record from database.
My issue is with writing the structure(consisting of character arrays) back to the file. I am using
fwrite(&record, sizeof(record), 1, out);
fwrite("\n", 1, 1, outfd);
This will write the data in the output file with a terminating NULL '\0' after each member. Please let me know how can I write this structure to the file without that terminating '\0' after each member.
Upvotes: 4
Views: 727
Reputation: 490088
This will write a record
out exactly as it's stored in memory -- but the compiler is free ti insert padding between the members, and if it does, this will write out whatever values happen to be in those padding bytes.
Many (most?) compilers have non-portable ways of preventing them from inserting that padding -- MSVC uses #pragma pack(1)
, gcc uses __attribute(__packed__)
(and at least some versions support the #pragma pack
syntax as well).
It's also possible that you've defined record
to include some zero bytes as part of the data (e.g., arrays of char with zero terminators to make them strings). Since you haven't shown the definition of record
, it's hard to guess whether this applies or not though.
Edit: based on your comment, it appears that the latter is the case. The first point I'd make is that removing these may not be a good idea. If you remove them, you'll have to do something to let a program reading the data know where one field ends and the next one begins (unless the fields are fixed width, which can be handled implicitly).
The most obvious possibility is to precede each field with its length. This has the advantage that if/when you want to seek through the file, you can get from one field to the next without reading through the data to find the terminating byte. Usually, however, I'd use an index instead -- a file containing the file offsets to successive records in the data (and possibly some key data for each record, so you can quickly search based on the contents of the records), so you can quickly seek to the location of a record and read its data. Unless you have extraordinarily large fields, seeking to individual fields rarely accomplishes much though.
Upvotes: 3
Reputation: 81684
I would imagine that those 0's are part of the character arrays -- they're at the end of every C string. If you need to write the strings to a file without the zeros, you could write the individual char arrays, writing only the characters and not the trailing zero (you might use strlen()
to find this length), ie.,
fwrite(theCharArray, 1, strlen(theCharArray), out);
But then you may need to write some information about the length of each string to the file.
Upvotes: 5