I tried to write a code which reads from file to stdout without stdio.h
. The problem is that the file does not stop at EOF.
Here is the code:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFF_SIZE 1024
#define EOF ???
int main(int argc, char * argv[]){
int file_desc = open(argv[1], O_RDWR);
char buff[BUFF_SIZE];
read(file_desc, buff, BUFF_SIZE);
int i = 0;
while ( buff[i] != EOF){
write(1, &buff[i], 1);
i++;
}
return 0;
}
Need an approach to break the loop if buff[i] == EOF
.
There is no character called "EOF". Some terminals have a character that they translate into an end-of-file indication, but you're not working with terminals here. The return value of read
tells you how many characters you read.
This code reads from a named file and writes to standard output without using <stdio.h>
for those operations. It uses fprintf(stderr, …)
to report errors because writing the equivalent code to use plain write()
is modestly frustrating — unless you use POSIX function dprintf()
, but that's declared in <stdio.h>
, even though it doesn't use file streams.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define BUFF_SIZE 1024
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s file\n", argv[0]);
return 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0)
{
fprintf(stderr, "%s: failed to open file '%s' for reading\n", argv[0], argv[1]);
return 1;
}
char buff[BUFF_SIZE];
int nbytes;
while ((nbytes = read(fd, buff, BUFF_SIZE)) > 0)
write(STDOUT_FILENO, buff, nbytes);
close(fd);
return 0;
}
The key point about detecting EOF is that read()
returns 0 bytes read when it detects EOF, or -1
on an error. So, there is more work to do when the number of bytes returned is strictly positive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.