- You need to ensure that
open
succeeded instead of blindly writing to the file-descriptor.
- Always check the return value of a syscall (and most C standard library functions) and check
errno
if the return value indicated an error.
- Your string literal will include a hidden
\0
(NULL
) character after the dot.
- Writing
text
directly to the file will therefore include the trailing \0
which is what you're seeing.
These issues can be rectified by:
Always checking the return value of a syscall - and in this case: print a helpful error message to stdout and perform any necessary cleanup (the goto closeFile;
statement).
- Because C doesn't have a native
try/catch
or RAII it means its difficult to write terse error-handling and cleanup code, but using goto
for common clean-up code is generally acceptable in C, hence the goto closeFile
statement.
Using strlen
to get the actual length of the string.
- Though in a pinch it's okay to use
sizeof(text) - 1
provided you're in a scope where the C compiler knows the length of text
as using sizeof()
won't work if you cross a function boundary due to array pointer decay.
Like so:
void writeToFile() {
int fd = open( "text1.txt", O_CREAT | O_WRONLY ); // Use `O_WRONLY` instead of `O_RDWR` if you're only writing to the file. Use `O_CREAT` to create a file if it doesn't already exist.
if( fd == -1 ) {
printf( "Error opening file: errno: %d - %s\n", errno, strerror( errno ) );
return;
}
size_t textLength = strlen( text );
size_t written = write( fd, text, textLength );
if( written == -1 ) {
printf( "Error writing text: errno: %d - %s\n", errno, strerror( errno ) );
goto closeFile;
}
else if( written < textLength ) {
printf( "Warning: Only %d of %d bytes were written.", written, textLength );
goto closeFile;
}
else {
// Carry on as normal.
}
closeFile:
if( close( fd ) == -1 ) {
printf( "Error closing file: errno: %d - %s\n", errno, strerror( errno ) );
}
}