简体   繁体   中英

How to write, read and delete a file in a single script in C programming

I created a file and filled it with some entries. However, I want to read this file and show it on the screen. Also, after showing the entries, I want it to be deleted with my permission. But I am stuck at this point please help me.

EDIT: Code is updated but still couldn't figure it out how to do:/

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

char name[20], surname[20], city[30], country[30], gender[15]; 
int count = 0;   

int main() {
    FILE *f1;
    f1 = fopen("C:\\FurkanArslan.txt", "r+");
    
    while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
        printf("\n*Please enter required information: \n");   
        
        printf("Name   :"); scanf("%s", name);
        printf("Surname:"); scanf("%s", surname);
        printf("Country:"); scanf("%s", country); 
        printf("City   :"); scanf("%s", city);
        printf("Gender :"); scanf("%s", gender);

        fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
        count++;    
    }
    
    fclose(f1); 
    
    printf("\n<<<<<%d data has been successfully saved!>>>> \n", count * 5);    
    printf("-------------------------------------\n");
    
    f1 = fopen("C:\\FurkanArslan.txt", "r");
    
    char c, answer; 
    while ((c = fgetc(f1)) != EOF)
        putchar(c);   // In this part I displayed file on the screen. 
    
    printf("\n\n <<<< %d entries are displayed on the screen! >>>>", count * 5);
        
    printf("\n\nWould you like to remove your file [Y/N] ?");
    scanf(" %c", &answer);
    
    if (answer == 'y' || answer == 'Y') {
        remove("f1");
        printf("\n\n***File successfully removed!");
    }
    return 0;
}

In order to show the content of a file you have to open it and read it letter by letter, after that, you can use the putchar function to output the current character

FILE *fp = fopen("path/to/file.txt","r");

char c;
while((c=fgetc(fp))!=EOF)
    putchar(c);

fclose(fp);

after that to remove a file you need to use the remove function, which receives the name of the file as paramter.

remove("my_file.txt");

There are multiple issues in your code:

  • there is no need to make the variables and arrays global, just define them in the body of the main() function.

  • you should tell scanf() the maximum number of characters to store in the destination array with a length specifier in the format string (eg: "%19s" ) and check for conversion success.

  • the variable c used in the reading loop must have type int for proper detection of EOF . fgetc() returns a positive byte value if successful and the special negative value EOF at end of file.

  • you do not need to reopen the file after writing to it. Sine you opened it for update mode, you can just seek back to the beginning of the file with rewind(f1) or fseek(f1, 0L, SEEK_SET) .

  • the file is open for read and update mode ("r+"): it will fail if the file does not exist. You should open it in write and update mode with "w+" to create or truncate it.

  • you should check that fopen succeeds at opening the file, otherwise you invoke undefined behavior passing a null stream pointer to fprintf .

  • to remove the file, remove() takes the filename as its argument. You must close the file before attempting to remove it.

Here is a modified version:

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

int main() {
    const char *filename = "C:\\FurkanArslan.txt";
    char name[20], surname[20], city[30], country[30], gender[15]; 
    int count = 0;   

    FILE *f1 = fopen(filename, "w+");
    if (f1 == NULL) {
        printf("Cannot open file %s.\n", filename);
        return 1;
    }

    while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
        printf("\n*Please enter required information: \n");   

        printf("Name   :"); if (scanf("%19s", name) != 1) break;
        printf("Surname:"); if (scanf("%19s", surname) != 1) break;
        printf("Country:"); if (scanf("%29s", country) != 1) break; 
        printf("City   :"); if (scanf("%29s", city) != 1) break;
        printf("Gender :"); if (scanf("%14s", gender) != 1) break;

        fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
        count++;    
    }

    printf("\n<<<<< %d data has been successfully saved to %s! >>>>\n",
           count * 5, filename);
    printf("-------------------------------------\n");

    rewind(f1); 

    int c; 
    while ((c = fgetc(f1)) != EOF)
        putchar(c);

    printf("\n\n <<<< %d entries are displayed on the screen! >>>>\n", count);
    fclose(f1);

    printf("\nWould you like to remove your file [Y/N] ?");
    char answer;
    if (scanf(" %c", &answer) == 1 && (answer == 'y' || answer == 'Y')) {
        if (remove(filename)) {
            printf("\n\n***Error removing file %s: %s\n",
                   filename, strerror(errno));
        } else {
            printf("\n\n***File %s successfully removed!\n", filename);
        }
    }
    return 0;
}

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