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 268 views
1 answer 274 views
1 answer 273 views
1 answer 279 views
279 views asked Dec 30, 2020 by avibootz
1 answer 263 views
263 views asked Dec 29, 2020 by avibootz
2 answers 384 views
...