D
D
Demium2015-02-01 13:29:39
C++ / C#
Demium, 2015-02-01 13:29:39

How to read a text file?

Help me understand and how to read a text file correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eddy_Em, 2015-02-01
@Eddy_Em

And you can do it like this:

gcc map.c -o map && ./map map.c
File contents:
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

typedef struct{
    char *data;
    size_t len;
} mmapbuf;

#define ERR(...) do{fprintf(stderr, __VA_ARGS__); exit(-1);}while(0)

mmapbuf *My_mmap(char *filename){
    int fd;
    char *ptr;
    size_t Mlen;
    mmapbuf *ret;
    struct stat statbuf;
    if(!filename) ERR("No filename given!");
    if((fd = open(filename, O_RDONLY)) < 0)
        ERR("Can't open %s for reading", filename);
    if(fstat (fd, &statbuf) < 0)
        ERR("Can't stat %s", filename);
    Mlen = statbuf.st_size;
    if((ptr = mmap (0, Mlen, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
        ERR("Mmap error for input");
    if(close(fd)) ERR("Can't close mmap'ed file");
    ret = malloc(sizeof(mmapbuf));
    ret->data = ptr;
    ret->len = Mlen;
    return  ret;
}

void My_munmap(mmapbuf *b){
    if(munmap(b->data, b->len))
        ERR("Can't munmap");
    free(b);
}


int main(int argc, char **argv){
  if(argc != 2) return 1;
  mmapbuf *readfile = My_mmap(argv[1]);
  printf("File contents:\n%s\n", readfile->data);
  My_munmap(readfile);
  return 0;
}

A
asd111, 2015-02-01
@asd111

In C, the most convenient way to read is through fscanf.

/* fscanf example */
#include <stdio.h>

int main ()
{
  char str [80];
  float f;
  FILE * pFile;

  pFile = fopen ("myfile.txt","w+");
  fprintf (pFile, "%f %s", 3.1416, "Hello");
  rewind (pFile);
  fscanf (pFile, "%f", &f);
  fscanf (pFile, "%s", str);
  fclose (pFile);
  printf ("I have read: %f and %s \n",f,str);
  return 0;
}

It will output
, and if there is C ++, then it is possible through input-output streams - it's even easier.
But of course this is a slow process. The fastest working way is to read a large chunk of the file and then process it.
habrahabr.ru/post/246257

V
Vladimir Martyanov, 2015-02-01
@vilgeforce

CreateFile/ReadFile/CloseHandle if Windows and want to use WinAPI

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question