user505145
user505145

Reputation: 11

C - Read a file without using iostream

Assume I have a file SomFoo.txt which contains a string of some length. Are there ways to read the file contents without using iostream ie (fread or fgets). I know the size of the file.

Upvotes: 1

Views: 1233

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 753515

Are you talking about C++ (where there is a header <iostream>) or about C where you're probably talking about file streams, aka FILE *, as found in <stdio.h> (or, in C++, in <cstdio>)?

Either way, on Unix and related systems, there are numerous system calls using file descriptors that are lower-level than the streams functions. The key, fundamental ones are:

  • open
  • close
  • read
  • write
  • lseek

There's also a large cast of others for specialized operations (sockets, pipes, asynchronous I/O, scatter/gather I/O, positioned I/O, etc).

Upvotes: 3

pcantin
pcantin

Reputation: 554

You could use embedded assembly code inside you C code.

Upvotes: 1

chacham15
chacham15

Reputation: 14251

lets go for a simple solution:

int File_read(char *filename, char *buffer){
    FILE *fp = fopen(filename, "rb"); //open the file
    if (fp == NULL){
        return 0; //indicate that the file does not exist
    }
    int length = 0;
    while ((current = fgetc(fp)) != EOF){ //get one char (note return value is an int)
        buffer[length] = current; //store the current char
        length = length + 1; //increase length
    }
    fclose(fp); //close the file
    return length; //no more chars, return length
}

Upvotes: 1

hlovdal
hlovdal

Reputation: 28180

You can use memory mapped io with mmap. Here is an example of reading the file /etc/fedora-release and print its content:

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define handle_error(_label, _text) do { perror(_text); goto _label; } while (0)

int main(int argc, char *argv[])
{
    char *addr;
    int fd;
    struct stat sb;
    size_t length;
    ssize_t s;

    fd = open("/etc/fedora-release", O_RDONLY);
    if (fd == -1) {
        handle_error(exit_failure, "open");
    }

    if (fstat(fd, &sb) == -1) {
        handle_error(exit_failure, "fstat");
    }
    length = sb.st_size;

    addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
    if (addr == MAP_FAILED) {
        handle_error(exit_failure, "mmap");
    }

    s = write(STDOUT_FILENO, addr, length);
    if (s != length) {
        if (s == -1) {
            handle_error(exit_failure, "write");
        }

        fprintf(stderr, "partial write");
        goto exit_failure;
    }

    exit(EXIT_SUCCESS);

exit_failure:
    exit(EXIT_FAILURE);
}

Upvotes: 1

Related Questions