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;
}
#include <stdio.h>
#include <string.h>
void run_main_program() {
FILE *file = fopen("employees.csv", "r"); // Step 1: Open file
if (!file) { // Step 2: Error check
printf("Error: Could not open file.\n");
}
else{
char line[100]; // Buffer to store each line
// Step 3: Read lines one by one
while (fgets(line, sizeof(line), file)) {
// Remove newline character at the end if present
line[strcspn(line, "\n")] = '\0';
// Split line into fields using comma as delimiter
char delimiter[] = ",";
char *field = strtok(line, delimiter);
// Step 4: Print each field with spacing
while (field != NULL) {
printf("%s ", field);
field = strtok(NULL, delimiter); // Keep splitting until found NULL
}
printf("\n"); // Newline after each row
}
fclose(file); // Step 5: Close the file
}
}
int main() {
run_main_program();
return 0;
}
Last updated