Reputation: 95
#include<stdio.h>
#include<fcntl.h>
int main(int argc, char *argv[])
{
char buffer[6];
int gotten;
printf("%s",argv[1]);
int fh = open(argv[1],O_RDONLY);
printf("File handle %d\n", fh);
while (gotten = read(fh, buffer, 6)) {
buffer[gotten] = '\0';
printf("%s", buffer);
}
return 0;
}
This part takes a file as input and prints the content of the file. The text file I am providing contains "hello". What does buffer[gotten] = '\0';
do in this code?
Upvotes: 2
Views: 1083
Reputation: 392833
It makes sure there is a NUL character to terminate a C-style string, to make it safe for use with printf
: https://en.wikipedia.org/wiki/Null-terminated_string
In C++ there are better types, like std::string
:
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <array>
#include <iostream>
int main(int argc, char *argv[]) {
if (argc < 2)
return -1;
std::array<char, 6> buffer;
printf("%s\n", argv[1]);
int fh = open(argv[1], O_RDONLY);
printf("File handle %d\n", fh);
while (int gotten = read(fh, buffer.data(), buffer.size())) {
std::cout.write(buffer.data(), gotten);
}
}
Upvotes: 1
Reputation: 409136
In C, char
strings are really called null terminated character strings. That '\0'
character is the "null terminator" (not to be confused with a null pointer).
If that's missing, all standard string functions will not work, as they will go out of bounds looking for it.
Because of the terminator, any string of e.g. 6 characters need space for at least 7 characters, to able to fit the terminator.
Upvotes: 0
Reputation: 310993
Strings in c are char
arrays where the last character of the string is the \0
character which marks the end of the string. Since reading the characters from the file doesn't include the \0
character, it needs to be added manually so it can be treated as a normal string.
Upvotes: 0
Reputation: 5706
Null terminates the string.
'\0'
is the null-termination character. gotten
is set by the read()
function which will return the number of characters read so buffer[gotten]
will be the next spot in the array (since it's 0-based).
The null-termination allows C to know when the string ends. Since you are reusing the buffer for every read it's impossible to know what will be in the buffer beforehand so manually null-terminating is the best option.
Upvotes: 0
Reputation: 326
The '\0' character is known as the string terminator. This lets string functions know that the string in the area of memory you pass to it is done. This helps avoid reading too far in memory.
Upvotes: 0
Reputation: 2978
It adds a null character ('\0'
) to the end of the string you read in. Without it, printing the value in buffer
might go past the end of "hello"
and potentially print garbage values.
Upvotes: 0