Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

c read file with read()

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define MAXLENGTH 256

int display(char* FILE) {
    int f = open(FILE, O_RDONLY); // we open the file in read only
    if (f == -1) { // open() returns -1 if there's an error
        perror("open");
        close(f);
        return 1;
    } else {
        char buffer[MAXLENGTH];
        int r = read(f, &buffer, MAXLENGTH);
        if(r == -1){ // read() returns -1 if there's an error
            perror("read");
            close(f);
            return 2;
        } else {
            write(1, buffer, r); 
            close(f);
            return 0;
        }
    }
}

int main(void) {
    display("file.txt");
    return 0;
}
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #read #file
ADD COMMENT
Topic
Name
2+6 =