C/file manipulation in c
Expert: Narendra - 9/28/2005
Questionhi 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
AnswerHere 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);
}