Building on Jeremy Friesner's answer, here's what I came up with. First, a function for counting the number of lines:
int countChar(char* str, char c) {
char* nextChar = strchr(str, c);
int count = 0;
while (nextChar) {
count++;
nextChar = strchr(nextChar + 1, c);
}
return count;
}
Next, a function for copying the string into an array of lines:
char** lineator(char* origin) {
char* str = (char*) malloc(strlen(origin) + 1);
strcpy(str, origin);
int count = countChar(origin, '\n');
char** lines = (char**) malloc(sizeof(char *) * count);
char* nextLine = strchr(str, '\n');
char* currentLine = str;
int i = 0;
while (nextLine) {
*nextLine = '\0';
lines[i] = malloc(strlen(currentLine) + 1);
strcpy(lines[i], currentLine);
currentLine = nextLine + 1;
nextLine = strchr(currentLine, '\n');
i++;
}
free(str);
return lines;
}
Then I use these two functions to read the lines one by one. For example:
int count = countChar (contents, '\n');
char** lines = lineator(contents);
const char equals[2] = "=";
for (int i = 0; i < count; i++) {
printf("%s\n", lines[i]);
}
I could of course use Mr. Freisner's answer. That would be more efficient and require fewer lines of code, but conceptually, I find this method a little easier to comprehend. I also neglected to deal with malloc failing.
fgets()
process input from aFILE
pointer. You can implement it yourself, a simple looping until new line or NULL is seen, keeping on a variable withstatic
storage class the offset where loop stoped and in next functions call you start from this offset. – Illusionarymatch
(IIRC) function in POSIX C does. So, the new line will be the area among this offsets defined by your function. – Illusionary