I’m trying to make some sort of simple console text editor program to get better with C. I’m having trouble with what I thought would be a somewhat simple task:

How do I get each line from my char* buffer, which contains all of my text, so I can output each line, including empty lines, with the correct line number in front of it.

I tried several different ways already, but none have stuck. I tried strtok(), which is what is currently pushed to my repo, and it ignores whitespace. I tried strchr() but did not have the slightest idea how that function worked and got an infinite loop. I tried doing my own function to create an array of lines but that lead to a segmentation fault which was not fixed by mallocing the array. I am at a loss here, I’m not sure what I can do.

Here is the repo: https://codeberg.org/Mister_Bones/txt-ed

Here is the offending code:

// Print contents of file
int print_file(char* buffer) {
	// Print a new line
	printf("\n");

	// Print each line with line number
	// Set first line
	int line_num = 1;

	// Get individual line from buffer
	char* line = strtok(buffer, "\n");

	// Loop through and print lines
	// TODO: Don't ignore whitespace
	while (line != NULL) {
		printf("%4d\t%s\n", line_num, line);
		line = strtok(NULL, "\n");
		line_num++;
	}

	return 0;
}
  • BlackRoseAmongThorns@slrpnk.net
    link
    fedilink
    arrow-up
    2
    ·
    2 days ago

    I’ll attempt to give a more hand wavey approach, but one that is hopefully easier to understand.

    First, implement:

    \\ find first index of `c` within string `str`.
    \\ returns true if found, sets `out` to result.
    \\ otherwise returns false.
    bool find(char* str, size_t len, char c, size_t* out)
    

    Now this can be used in a loop, where you supply a slice starting at the last line (or the beginning of the slice, on the first iteration), where len is the length of the original string minus the amount of characters consumed (index of the beginning of the slice, relative to the start of the original string).

    Note this requires calculating the string length beforehand, if this is a c-string (as in null terminated).

    This should be relatively simpler to understand and implement than what the standard library supplies, sadly the C standard library is not easy to use or very reliable, so you’ll mostly have to make do yourself.

    I hope this helped, I’m currently away from a computer so i can’t give a code example, good luck.