HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcMinor

C program to write 5 lines to a file then print the lines except the second line

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filethelineprogramwriteprintsecondthenexceptlines

Problem

This will read 5 lines into a file from stdin, then print all the lines except the second one.

I used an array because I'm not sure how to do dynamic memory allocation.

#include 
#include 
#define MAX_SIZE 1024

void write_to_file(const char *s);
void print_file(const char *s);

int main(void){
    const char file_name[] = "text";
    write_to_file(file_name);
    print_file(file_name);

    return 0;
}

void write_to_file(const char *s){
    FILE *in_file;
    if((in_file = fopen(s, "w")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }

    char buffer[MAX_SIZE];
    for(int i = 0; i < 5; ++i){
        fgets(buffer, sizeof(buffer), stdin);
        fputs(buffer, in_file);
    }

    fclose(in_file);
}

void print_file(const char *s){
    FILE *in_file;
    if((in_file = fopen(s, "r")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }
    int c;
    int flag = 0;
    while((c = fgetc(in_file)) != EOF){
        printf("%c", c);
        if((flag == 0) && (c == '\n')){
            while((c = fgetc(in_file)) != '\n'){
                /*skip the second line*/
            }
            flag = 1;
        }
    }
}

Solution

You have the right idea in write_to_file(), but print_file() is awkward.

There is no need to work a character at a time in print_file(). You can read a line at a time using fgets(buffer, sizeof(buffer), in_file).

Avoid flag variables. Here, you could use a for loop to track the line number instead.

char buffer[MAX_SIZE];
for (int i = 0; fgets(buffer, sizeof(buffer), in_file) != EOF; ++i) {
    if (i != 1) puts(buffer);
}

Code Snippets

char buffer[MAX_SIZE];
for (int i = 0; fgets(buffer, sizeof(buffer), in_file) != EOF; ++i) {
    if (i != 1) puts(buffer);
}

Context

StackExchange Code Review Q#161301, answer score: 4

Revisions (0)

No revisions yet.