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;
}
  • wicked@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    4 days ago

    Before trying to learn and use the standard library, I’d advise you to write a few simple functions yourself:

    1. void print_until(const char* str, char c) - print every character in str until you see c or null (Note: Don’t print the c or null, which should ensure that a str that only contains a \0 doesn’t crash.)
    2. const char* print_until_2(const char* str, char c) - as before, but return the pointer to where you found c or null
    3. void print_delimited_by(const char* str, char delimiter, char separator) - use print_until_2 in a while-loop, don’t print the delimiter, but do print a separator.

    For example, print_delimited_by("1;2;3",';',',') should print 1,2,3.

    Finally, void num_delimited_by(const char* str, char del) - like print_delimited_by, but add a number before every output, and use newline as the separator.

    These fundamental string exercises will give you a solid foundation for understanding oantby’s explanations about the standard library. Note that no memory allocation is necessary.