Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing the structure to a file in C

Tags:

c

file

structure

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.

like image 615
Sachin Chourasiya Avatar asked Feb 23 '23 19:02

Sachin Chourasiya


1 Answers

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.

like image 101
Ernest Friedman-Hill Avatar answered Mar 03 '23 03:03

Ernest Friedman-Hill