简体   繁体   中英

How to know if it is EOF without stdio.h?

Problem

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;
}

Code Explanation

  1. includes above the code imports: open(), read() and write() functions which are all linux syscalls.
  2. for now buffer size is 1024.
  3. EOF is not known.
    • tried (-1) as it's defined in stdio.h
    • tried 0x03 and 0x04 hex codes for CTRL+D and CTRL+C.
    • tried 0x1a hex code for CTRL+Z.
  4. file_desc is an integer type stores a file descriptor with filename argv[1].
  5. reading file_desc data into buffer.
  6. a loop to write from buffer to STDIN which is 1 until buffer is EOF.

What do I want?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM