File: fileio.cpp

package info (click to toggle)
meshoptimizer 0.15%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,148 kB
  • sloc: cpp: 11,845; ansic: 6,343; javascript: 305; makefile: 109; python: 24
file content (107 lines) | stat: -rw-r--r-- 2,016 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"

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

#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif

TempFile::TempFile(const char* suffix)
    : fd(-1)
{
#if defined(_WIN32)
	const char* temp_dir = getenv("TEMP");
	path = temp_dir ? temp_dir : ".";
	path += "\\gltfpack-XXXXXX";
	(void)_mktemp(&path[0]);
	path += suffix;
#elif defined(__wasi__)
	static int id = 0;
	char ids[16];
	sprintf(ids, "%d", id++);

	path = "gltfpack-temp-";
	path += ids;
	path += suffix;
#else
	path = "/tmp/gltfpack-XXXXXX";
	path += suffix;
	fd = mkstemps(&path[0], strlen(suffix));
#endif
}

TempFile::~TempFile()
{
	remove(path.c_str());

#ifndef _WIN32
	close(fd);
#endif
}

std::string getFullPath(const char* path, const char* base_path)
{
	std::string result = base_path;

	std::string::size_type slash = result.find_last_of("/\\");
	result.erase(slash == std::string::npos ? 0 : slash + 1);

	result += path;

	return result;
}

std::string getFileName(const char* path)
{
	std::string result = path;

	std::string::size_type slash = result.find_last_of("/\\");
	if (slash != std::string::npos)
		result.erase(0, slash + 1);

	std::string::size_type dot = result.find_last_of('.');
	if (dot != std::string::npos)
		result.erase(dot);

	return result;
}

bool readFile(const char* path, std::string& data)
{
	FILE* file = fopen(path, "rb");
	if (!file)
		return false;

	fseek(file, 0, SEEK_END);
	long length = ftell(file);
	fseek(file, 0, SEEK_SET);

	if (length <= 0)
	{
		fclose(file);
		return false;
	}

	data.resize(length);
	size_t result = fread(&data[0], 1, data.size(), file);
	int rc = fclose(file);

	return rc == 0 && result == data.size();
}

bool writeFile(const char* path, const std::string& data)
{
	FILE* file = fopen(path, "wb");
	if (!file)
		return false;

	size_t result = fwrite(&data[0], 1, data.size(), file);
	int rc = fclose(file);

	return rc == 0 && result == data.size();
}