Question

I'm trying to write a title to a file but this will be read by another program which is looking for 80 bytes. How can I write a string of size 80 bytes that may contain a small amount of characters such as "box"?

what i've tried:

const char* title;
GetAttribute(model,"title of attar",&title);  //args 2 & 3 must be char *, char **
char newtitle[80];
strcopy(newtitle,title);

fwrite(newtitle,sizeof(char),80,fp);

I also tried writing just the title...

fwrite(newtitle,sizeof(char),strlen(title),fp);

and padding with white space after for the remaining bytes, but the spaces cause issues later on in the program thanks for the suggestions

Était-ce utile?

La solution

You probably want to pad it with 0 bytes. Fill your newtitle buffer with zeroes before copying the string into it, then write that buffer to the file:

char newtitle[80];
memset(newtitle, '\0', 80);
strncpy(newtitle, title, 80);

fwrite(newtitle, sizeof(char), 80, fp);

You can pass whatever ASCII character you want into memset(), to pad it with. But with binary files you'll generally use '\0'.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top