FGETS()

this function is used to read from a file one line at a time

char line[256];
while (fgets(line, sizeof(line), file)) {
    printf("%s", line);
}
#include <stdio.h>

// Function to read and print contents of config.txt line by line
void run_main_program() {
    // Step 1: Open the file in read mode
    FILE *file = fopen("/home/chef/workspace/config.txt", "r");

    // Step 2: Check if the file opened successfully
    if (file == NULL) {
        printf("Error: Unable to open configuration file.\n");
        return 1;
    }
    else{
        // Step 3: Read each line using fgets()
        char line[256];  // Buffer to store each line
        while (fgets(line, sizeof(line), file)) {
            line[strcspn(line, "\n")] = '\0';
            
            // Step 4: Print the line
            printf("%s", line);
        }

        // Step 5: Close the file after reading
        fclose(file);
    }
}

// Main function
int main() {
    run_main_program();
    return 0;
}

Last updated