I wrote a program to test writing a char[128] array to file using write() function in C. The following is my code, however, after writing, I can see that the string "testseg" is followed by a "d" or "È" in the testFile.txt file. Is this a proper way of writing char[] array to file?
int main()
{
char pathFile[MAX_PATHNAME_LEN];
sprintf(pathFile, "testFile.txt");
int filedescriptor = open(pathFile, O_RDWR | O_APPEND | O_CREAT, 0777);
int num_segs = 10;
int mods = 200;
const char *segname = "testseg"; /* */
char real_segname[128];
strcpy(real_segname, segname);
write(filedescriptor, &num_segs, sizeof(int));
write(filedescriptor, real_segname, strlen(real_segname));
printf("real_segname length is %d \n", (int) strlen(real_segname));
write(filedescriptor, &mods, sizeof(int));
close(filedescriptor);
return 0;
}
strncpy(real_segname, segname, sizeof(real_segname);and thenwrite(filedescriptor, real_segname, sizeof(real_segname));— or by including a length before the string:short s = strlen(segname); write(filedescriptor, &s, sizeof(s)); write(filedescriptor, real_segname, s);.testseg? Because you're writingmodsafter that. Could that be it?writefunction writes binary data. If you want the numbers to be human readable you should print them to a string using sprintf and then write that string. You may also want to add a new line character'\n'