Reputation: 441
My code is working fine. The only error I'm getting is that after the program writes the text into the file i.e. text1.txt, the text file prints some weird symbols like /00 when I actually open it.
int fd;
fd = open("text1.txt", O_RDWR);
char text[] = "This is my file.";
write(fd,text,sizeof(text));
Upvotes: 2
Views: 2946
Reputation: 155270
open
succeeded instead of blindly writing to the file-descriptor.
errno
if the return value indicated an error.\0
(NULL
) character after the dot.
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).
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.
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 ) );
}
}
Upvotes: 4