user3753834
user3753834

Reputation: 369

C - How do i read all lines of a file

Im unsure how to read all the lines of a file, atm it only reads the first line of the code in the text file. Can someone show me how to make it read all the lines?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{

    FILE *fp;
    fp = fopen("specification.txt", "r");

    char ** listofdetails; 

    listofdetails = malloc(sizeof(char*)*6);
    listofdetails[0] = malloc(sizeof(char)*100);

    fgets(listofdetails[0], 100, fp);


    /*strcpy(listofdetails[0], "cars");*/

    printf("%s \n", listofdetails[0]);


    free(listofdetails[0]);
    free(listofdetails);
    fclose(fp);

    return 0;
}

MY text file:

10X16 de4 dw9 ds8 g8,7 m3,4 h6,5 p2,2 
10X16 de4 dw9 ds8 g8,7 m3,4 h6,5 p2,2
10X16 de4 dw9 ds8 g8,7 m3,4 h6,5 p2,2

Upvotes: 2

Views: 18068

Answers (5)

Marco
Marco

Reputation: 7261

#include <stdio.h>
#include <assert.h>

int main(int argc, const char * argv[])
{
    FILE *file = fopen("specification.txt", "r");
    char currentline[100];
    
    assert(file != NULL);
    
    while (fgets(currentline, sizeof(currentline), file) != NULL) {
        fprintf(stderr, "got line: %s\n", currentline);
        /* Do something with `currentline` */
    }
        
    (void)fclose(file);
}

Upvotes: 5

macfij
macfij

Reputation: 3209

another example: you can use getline if you're targetting a POSIX platform. it allocates space needed to store the line, but you must free it by yourself. if there's an error or EOF, getline returns -1.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{

    FILE *fp;
    fp = fopen("specification.txt", "r");
    char** listofdetails; 
    int ROWS = 6;
    listofdetails = calloc(ROWS,sizeof(char*));

    int i;
    size_t len;
    ssize_t readed;
    for (i = 0; i < ROWS; i++) {
        if ((readed = getline(&listofdetails[i], &len, fp)) == -1) {
            break;
        }
    }

    for (i = 0; i < ROWS; i++) {
        if (listofdetails[i] == NULL) {
            break;
        }
        printf("%s\n",listofdetails[i]);
        free(listofdetails[i]);
    }

    fclose(fp);
    free(listofdetails);

    return 0;
}

Upvotes: 0

Use getline(3), assuming your OS & libc is Posix2008 compliant (eg. on Linux):

FILE *fp = fopen("specification.txt", "r");
if (!fp) { perror("specification.txt"); exit(EXIT_FAILURE); };
size_t sizelist = 6; // initial guess of number of lines
size_t nblines = 0;
char ** listofdetails = calloc(sizelist, sizeof(char*));
if (!listofdetails) { perror("initial calloc"); exit(EXIT_FAILURE); };
char*curline = NULL;
size_t cursize = 0;
do {
   ssize_t curlen = getline(&curline, &cursize, fp);
   if (curlen < 0) break;
   if (nblines >= sizelist) {
      size_t newsizelist = 3*sizelist/2+5;
      char**newlist = calloc(newsizelist, sizeof(char*));
      if (!newlist) { perror("growing calloc"); exit(EXIT_FAILURE); };
      memcpy (newlist, sizelist, nbline*sizeof(char*));
      sizelist = newsizelist;
   };
   if (!(sizelist[nblines++] = strdup(curline))) 
     { perror("strdup"); exit(EXIT_FAILURE); };
} while (!feof(fp));

The above code can accept as much lines, and as large lines, as the system resources allow. On my powerful laptop (16Gbytes RAM), i might be able to read a file of more than a million lines, each of nearly a thousand chars (or a file of a single line of many millions chars).

At the end (of your program) you should better free memory:

for (size_t ix=0; ix<nblines; ix++) {
   free(sizelist[ix]), sizelist[ix] = NULL;
}
free(sizelist), sizelist = NULL;
free(curline), curline = NULL; cursize = 0;

Upvotes: 1

szpal
szpal

Reputation: 647

If you want read the 'specification.txt' text-file line by line, you can do that this way:

  char  row[255];
  FILE  *fp;

  fp = fopen( "specification.txt", "r" );

  if ( fp == NULL ) {
    // error handling..
  }

  while ( fgets( row, sizeof( row ), fp ) != NULL ) {
    puts( row );
  }

  fclose( fp );

Make sure, your 'row' buffer large enough.

Upvotes: 2

Nematollah Zarmehi
Nematollah Zarmehi

Reputation: 694

You can read the whole file in the following manner:

char *buffer;
FILE *fp = fopen("filename.txt", "rb");
if (fp != NULL)
{
    fseek(fp, 0L, SEEK_END);
    long stell = ftell(fp);
    rewind(fp);
    buffer = (char *)malloc(stell);
    if (buffer != NULL)
    {
        fread(buffer, stell, 1, fp);
        fwrite(buffer, stell, 1, stdout);
        fclose(fp);
        fp = NULL;
        free(buffer);
    }
}

The above code reads the filename.txt file and print it out to the stdout.

Upvotes: -1

Related Questions