Programming Fundamentals/Files/C

From Wikiversity
Jump to navigation Jump to search

files.c[edit | edit source]

// This program creates a file, adds data to the file, displays the file,
// appends more data to the file, displays the file, and then deletes the file.
// It will not run if the file already exists.
//
// References
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Programming

#include <stdio.h>

void create_file(char *filename);
void read_file(char *filename);
void append_file(char *filename);
void delete_file(char *filename);
int file_exists(char *filename);

int main()
{
    char FILENAME[] = "~file.txt";

    if(file_exists(FILENAME))
    {
        printf("File already exists.\n");
    }
    else
    {
        create_file(FILENAME);
        read_file(FILENAME);
        append_file(FILENAME);
        read_file(FILENAME);
        delete_file(FILENAME);
    }
}

void create_file(char *filename)
{
    FILE *file;
    float c;
    float f;
    
    file = fopen(filename, "w");
    fprintf(file, "C\tF\n");
    for(c = 0; c <= 50; c++)
    {
        f = c * 9 / 5 + 32;
        fprintf(file, "%.1f\t%.1f\n", c, f);
    }
    fclose(file);
}

void read_file(char *filename)
{
    FILE *file;
    char line[256];

    file = fopen(filename, "r");
    while(!feof(file))
    {
        fgets(line, sizeof(line), file);
        printf("%s", line);
    }
    fclose(file);
    printf("\n");
}

void append_file(char *filename)
{
    FILE *file;
    float c;
    float f;
    
    file = fopen(filename, "a");
    for(c = 51; c <= 100; c++)
    {
        f = c * 9 / 5 + 32;
        fprintf(file, "%.1f\t%.1f\n", c, f);
    }
    fclose(file);
}

void delete_file(char *filename)
{
    remove(filename);
}

int file_exists(char *filename)
{
    FILE *file;
    
    file = fopen (filename, "r");
    if (file != NULL)
    {
        fclose (file);
    }
    return (file != NULL);
}

Try It[edit | edit source]

Copy

See Also[edit | edit source]