C - How to read line by line?

In my C program, I have a line that I want to process one line at a time, ideally, keeping each line in another line, doing what I want with the specified line, and then repeating. I have no idea how this will be achieved.

I thought to use sscanf. Is there a read pointer in sscanf, as if I were reading from a file? What would be an alternative for this?

+4
source share
1 answer

Here is an example of how you can do this efficiently if you are allowed to write to a long string:

#include <stdio.h> #include <string.h> int main(int argc, char ** argv) { char longString[] = "This is a long string.\nIt has multiple lines of text in it.\nWe want to examine each of these lines separately.\nSo we will do that."; char * curLine = longString; while(curLine) { char * nextLine = strchr(curLine, '\n'); if (nextLine) *nextLine = '\0'; // temporarily terminate the current line printf("curLine=[%s]\n", curLine); if (nextLine) *nextLine = '\n'; // then restore newline-char, just to be tidy curLine = nextLine ? (nextLine+1) : NULL; } return 0; } 

If you are not allowed to write to a long line, then you will need to create a temporary line for each line so that the NUL line is completed. Something like that:

 #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char ** argv) { const char longString[] = "This is a long string.\nIt has multiple lines of text in it.\nWe want to examine each of these lines separately.\nSo we will do that."; const char * curLine = longString; while(curLine) { const char * nextLine = strchr(curLine, '\n'); int curLineLen = nextLine ? (nextLine-curLine) : strlen(curLine); char * tempStr = (char *) malloc(curLineLen+1); if (tempStr) { memcpy(tempStr, curLine, curLineLen); tempStr[curLineLen] = '\0'; // NUL-terminate! printf("tempStr=[%s]\n", tempStr); free(tempStr); } else printf("malloc() failed!?\n"); curLine = nextLine ? (nextLine+1) : NULL; } return 0; } 
+6
source

Source: https://habr.com/ru/post/1494606/


All Articles