TextFile.cxx 1.95 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20
#include "config.h"
21
#include "TextFile.hxx"
22
#include "util/Alloc.hxx"
23 24 25
#include "fs/Path.hxx"
#include "fs/FileSystem.hxx"

26 27
#include <assert.h>
#include <string.h>
28
#include <stdlib.h>
29

30
TextFile::TextFile(Path path_fs)
31
	:file(FOpen(path_fs, FOpenMode::ReadText)),
32
	 buffer((char *)xalloc(step)), capacity(step), length(0) {}
33 34 35

TextFile::~TextFile()
{
36 37
	free(buffer);

38 39 40 41
	if (file != nullptr)
		fclose(file);
}

42
char *
43
TextFile::ReadLine()
44
{
45
	assert(file != nullptr);
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60
	while (true) {
		if (length >= capacity) {
			if (capacity >= max_length)
				/* too large already - bail out */
				return nullptr;

			capacity <<= 1;
			char *new_buffer = (char *)realloc(buffer, capacity);
			if (new_buffer == nullptr)
				/* out of memory - bail out */
				return nullptr;
		}

		char *p = fgets(buffer + length, capacity - length, file);
61
		if (p == nullptr) {
62
			if (length == 0 || ferror(file))
63
				return nullptr;
64 65 66
			break;
		}

67 68
		length += strlen(buffer + length);
		if (buffer[length - 1] == '\n')
69 70 71
			break;
	}

72
	/* remove the newline characters */
73
	if (buffer[length - 1] == '\n')
74
		--length;
75
	if (buffer[length - 1] == '\r')
76 77
		--length;

78 79 80
	buffer[length] = 0;
	length = 0;
	return buffer;
81
}