Skip to content

Instantly share code, notes, and snippets.

@suragch
Created May 4, 2022 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suragch/6e4c0c982867afff6838e3dd3906b38a to your computer and use it in GitHub Desktop.
Save suragch/6e4c0c982867afff6838e3dd3906b38a to your computer and use it in GitHub Desktop.
Formatting a text file in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE* getTextFromFile(char filename[]) {
FILE* ptr;
ptr = fopen("data.csv", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
return ptr;
}
const char* getLine(FILE* file) {
// TODO: this is broken
char myMemory[256];
char * line;
char ch;
int index = 0;
do {
ch = fgetc(file);
if (ch == '\n') {
break;
} else {
// Sementation fault error
line[index] = ch;
}
index++;
} while (ch != EOF);
//printf("%d\n", index);
line[index] = '\0';
return line;
}
int main()
{
// 1. Get the text from the file
FILE* file = getTextFromFile("data.csv");
// 2. Get one line of text
const char* line = getLine(file);
printf("%s", line);
fclose(file);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment