How to create, write, read, and remove a file in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char* fname = "d:/info.txt";
    int status = EXIT_FAILURE;

    FILE* fp = fopen(fname, "w+");
    if (!fp) {
        perror("File opening failed");
        return status;
    }
    fputs("text to write to file\n", fp);
    rewind(fp);

    int ch;
    while ((ch = fgetc(fp)) != EOF) {
        putchar(ch);
    }

    if (ferror(fp)) {
        puts("Error reading file");
    }
    else if (feof(fp)) {
        puts("End of file - success");
        status = EXIT_SUCCESS;
    }

    fclose(fp);
    remove(fname);

    return status;
}



/*
run:

text to write to file
End of file - success

*/

 



answered Apr 19, 2024 by avibootz

Related questions

1 answer 162 views
1 answer 162 views
1 answer 156 views
1 answer 169 views
169 views asked Dec 30, 2020 by avibootz
1 answer 170 views
170 views asked Dec 29, 2020 by avibootz
2 answers 221 views
...