Read file line by line in C and C++

fileRead.c

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

#define bufSize 1024

int main(int argc, char *argv[])
{
  FILE* fp;
  char buf[bufSize];
  if (argc != 2)
  {
    fprintf(stderr,
            "Usage: %s <soure-file>\n", argv[0]);
    return 1;
  }
  if ((fp = fopen(argv[1], "r")) == NULL)
  { /* Open source file. */
    perror("fopen source-file");
    return 1;
  }

  while (fgets(buf, sizeof(buf), fp) != NULL)
  {
    buf[strlen(buf) - 1] = '\0'; // eat the newline fgets() stores
    printf("%s\n", buf);
  }
  fclose(fp);
  return 0;
}

fileRead.cpp

#include <iostream>
#include <string>
#include <fstream>

int main() {

  std::ifstream infile("Team.txt");
  std::string line;
  while (std::getline(infile, line)) {
    std::cout << line << std::endl;
  }

  return 0;
}

This code was developed by me, G. Samaras.

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

2 thoughts on “Read file line by line in C and C++

  1. *I Want to read a set of data contains in a file which are in different types ( int, double and string types) string type data contain more than one word ,

    file type is txt file

    It contains files in following pattern bookid (intiger) book category (string) book name ( string) book price ( double) each data is in seperate lines and no label is there as I types only values and names are there

    how to read them and print? please help me to fix this issues*

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s