Reputation: 18875
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;
}
Upvotes: 1
Views: 2164
Reputation: 153348
...writing a char[128] array to file ...I can see that the string "testseg" ...
is a contradiction.
In C, a string is an array of char
followed by and including a '\0'
and
a char[128]
is a fixed 128 char
in length.
When code does write(filedescriptor, real_segname, strlen(real_segname));
, it does neither. It is not writing a C string, 7 char
of "testseg" terminated with a '\0'
. Instead it just wrote the 7 char
and no terminating '\0'
. Neither did it write 128 char
.
One could instead perform write(filedescriptor, real_segname, strlen(real_segname)+1);
to write the 7 char
and the terminating '\0'
. Or write the length and then the interesting parts of the arry. Or write the entire 128 char
array`. Need to identify how you want to read data back and other coding goals to well advise.
As @SGG suggests, the unusually char
are simply the result of write(filedescriptor, &mods, sizeof(int));
and are not part of your unterminated array.
Upvotes: 2
Reputation: 2728
after writing, I can see that the string "testseg" is followed by a "d" or "È" in the testFile.txt file
Why it is showing "d" or "È"??
Only try below write
function (in your code, comment remaining write calls except below call)
write(filedescriptor, &mods, sizeof(int));
Now see the contents of testFile.txt
(cat testFile.txt
). It shows some junk value(s).
Because, all .txt
files will show you in the form of ASCII text
format. It converts every byte into ASCII
charcter. String and characters you're writing in ASCII format and reading them as ASCII. So no problem. But here you're writing mods and num_segs
as integers and reading them as ASCII format. So you got those junk values.
Is this a proper way of writing char[] array to file?
Yes, according to man pages you're writing them in proper way. And please make sure to validate your function calls(write
). Where to write, what to write in a file depends upon your requirement.
Upvotes: 1