You are here:

C/file manipulation in c

Advertisement


Question
hi sir,
i want to read a file and display the contents of the file. how do i go about doing it. Example...a names.txt is a file and it contains all the names of the people. so the program should read the names.txt file and display all the names upon running the program. thanks for helping me.
sudha

Answer
Here is the code and you can directly use this.
Please let me know if you face any problem while using this:

#include <stdio.h>

#define BUFSIZE 1024

void usage(char *cmd)
{
  printf("Usage: %s <file to read with complete path>\n", cmd);
  printf("If your file is at /home/sudha/documents/names.txt, then the command will be: \n");
  printf("%s /home/sudha/documents/names.txt\n", cmd);
}

int main(int argc, char *argv[])
{
  FILE *fp;

  if (argc < 2)
  {
      usage(argv[0]);
      exit(0);
  }

  fp = fopen(argv[1], "r");
  if (fp == NULL)
  {
     usage(argv[0]);
     exit(0);
  }

  printf("Contents of %s are: \n", argv[1]);

  while (!feof(fp))
  {
     char buf[BUFSIZE] = {0};

     fread(buf, sizeof(char), BUFSIZE, fp);
     printf("%s", buf);
  }

  printf("End of the file\n");

  fclose(fp);
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.