Přidat otázku mezi oblíbenéZasílat nové odpovědi e-mailem Čtení řetězců v Céčku

Lol, to vyzerá, že si si neprišiel po radu ako to napísať, ale po riešenie.

Tá možnosť 2 by mohla vyzerať takto:

#include <stdio.h>
#include <stdlib.h>

char* get_line(char** start) {
	char* result = *start;
	char* c = *start;
	if (!*c) {
		return NULL;
	}
	while (*c) {
		switch (*c) {
			case '\r':
				*c++ = '\0';
				if (*c == '\n') {
					++c;
				}
				*start = c;
				return result;

			case '\n':
				*c++ = '\0';
				*start = c;
				return result;

			default:
				++c;
				break;
		}
	}
	return result;
}

int main() {
	FILE* fp = fopen("vstup.txt", "rb");
	if (!fp) {
		perror("Failed to open file 'vstup.txt'");
		return EXIT_FAILURE;
	}

	if (fseek(fp, 0, SEEK_END) != 0) {
		perror("Failed to seek the end of file");
		return EXIT_FAILURE;
	}

	long fsize = ftell(fp);
	if (fsize == -1L) {
		perror("Failed to get file position");
		return EXIT_FAILURE;
	}

	rewind(fp);

	char *file_content = malloc(fsize + 1);
	if (file_content == NULL) {
		perror("Failed to allocate memory for file content");
		return EXIT_FAILURE;
	}

	if (fread(file_content, 1, fsize, fp) != fsize) {
		perror("Failed to read file content");
		return EXIT_FAILURE;
	}

	fclose(fp);

	file_content[fsize] = 0;

	char *start = file_content;
	char *a = get_line(&start);
	char *b = get_line(&start);
	char *c = get_line(&start);
	char *d = get_line(&start);

	printf("a = %s\n", a);
	printf("b = %s\n", b);
	printf("c = %s\n", c);
	printf("d = %s\n", d);

	free(file_content);
}

Výstup pre tvoj vstupný súbor potom vyzerá takto:

a = auto
b = dinosaurusREX
c = pcporadnajenejlepsiporadna
d = (null)

Čítam binárne, lebo chcem mať v pamäti presne to, čo je v súbore. Mohol by si to čítať aj textovo, ale to vyžaduje pár úprav (get_line bude jednoduchší, ale fread bude trochu zložitejší, pretože nerozlišuje medzi chybou a koncom súboru - viď dokumentácia).

Reakce na odpověď

1 Zadajte svou přezdívku:
2 Napište svou odpověď:
3 Pokud chcete dostat ban, zadejte libovolný text:

Zpět do poradny