Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <stdio.h> #include <stdlib.h> #include <string.h> int write_csv(const char *path) { FILE *f = fopen(path, "w"); if (!f) { perror(path); return -1; } fprintf(f, "name,score,grade "); fprintf(f, "Alice,%d,%s ", 95, "A"); fprintf(f, "Bob,%d,%s ", 82, "B"); fprintf(f, "Carol,%d,%s ", 74, "C"); fclose(f); return 0; } int read_csv(const char *path) { FILE *f = fopen(path, "r"); if (!f) { perror(path); return -1; } char line[128]; int row = 0; while (fgets(line, sizeof(line), f)) { /* Strip trailing newline */ line[strcspn(line, " ")] = '\0'; if (row == 0) { printf("Header: %s ", line); } else { char name[32]; int score; char grade[4]; if (sscanf(line, "%31[^,],%d,%3s", name, &score, grade) == 3) printf(" %-8s score=%-3d grade=%s ", name, score, grade); } row++; } if (ferror(f)) perror("read error"); fclose(f); return 0; } int main(void) { const char *path = "scores.csv"; if (write_csv(path) == 0) read_csv(path); return EXIT_SUCCESS; }
Result
Open