简体   繁体   中英

How to read and print the contents of a txt file in C

I am trying to find an easier way of reading a text file. I have never programed in C before so this is all new to me. My goal is to be able to run my program and have it automatically print to the screen. What I have below works but I have to enter the file in every time. Any help would be greatly appreciated.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char ch, file_name[25];
    FILE *fp;

       printf("Enter name of a file you wish to see\n");
       gets(file_name);

       fp = fopen(file_name, "r"); // read mode

       if (fp == NULL)
       {
          perror("Error while opening the file.\n");
          exit(EXIT_FAILURE);
       }

       printf("The contents of %s file are:\n", file_name);

       while((ch = fgetc(fp)) != EOF)
          printf("%c", ch);

       fclose(fp);
       return 0;
}

This is the output:

Enter name of a file you wish to see
warning: this program uses gets(), which is unsafe.
Data.txt
The contents of Data.txt file are:
1
2
3
4
5
6
7
8
9
10

Will you always be reading from Data.txt? If so you can hardcode the file name and replace gets(file_name); with char * file_name = "Data.txt" . If you do this also remove the current definition of file_name to avoid a redefinition error.

There are a few ways to define the filename without user intervention. In all cases, remove

printf("Enter name of a file you wish to see\n");
gets(file_name);

Replace gets(file_name); with strcpy(file_name, "Data.txt"); .

You will need to also #include <string.h> .


Replace file_name[25] with file_name[] = "Data.txt"


Replace char ch, file_name[25]; with char ch; char *file_name = "Data.txt"; char ch; char *file_name = "Data.txt"; You could also declare the string as constant: const char *file_name = "Data.txt"; .


Replace gets(file_name); with snprintf(file_name, (sizeof(file_name)/sizeof(file_name[0]))-1, "Data.txt");

sizeof(file_name)/sizeof(file_name[0]) calculates the maximum length of the array by dividing the total array's size by the length of a single element. We subtract 1 to reserve an element for the string termination character '\0' .

snprintf() would allow you to build the filename programmatically.


Remove , file_name[25] .

Replace fp = fopen(file_name, "r"); with fp = fopen("Data.txt", "r"); .

Replace printf("The contents of %s file are:\n", file_name); with printf("The contents of the file are:\n");

(Note the loss of functionality)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM