1 // Copyright (c) 2016 Google Inc.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #ifndef LIBSPIRV_TOOLS_IO_H_
16 #define LIBSPIRV_TOOLS_IO_H_
22 // Appends the content from the file named as |filename| to |data|, assuming
23 // each element in the file is of type |T|. The file is opened with the given
24 // |mode|. If |filename| is nullptr or "-", reads from the standard input. If
25 // any error occurs, writes error messages to standard error and returns false.
27 bool ReadFile(const char* filename, const char* mode, std::vector<T>* data) {
28 const int buf_size = 1024;
29 const bool use_file = filename && strcmp("-", filename);
30 if (FILE* fp = (use_file ? fopen(filename, mode) : stdin)) {
32 while (size_t len = fread(buf, sizeof(T), buf_size, fp)) {
33 data->insert(data->end(), buf, buf + len);
35 if (ftell(fp) == -1L) {
37 fprintf(stderr, "error: error reading file '%s'\n", filename);
41 if (sizeof(T) != 1 && (ftell(fp) % sizeof(T))) {
42 fprintf(stderr, "error: corrupted word found in file '%s'\n", filename);
46 if (use_file) fclose(fp);
48 fprintf(stderr, "error: file does not exist '%s'\n", filename);
54 // Writes the given |data| into the file named as |filename| using the given
55 // |mode|, assuming |data| is an array of |count| elements of type |T|. If
56 // |filename| is nullptr or "-", writes to standard output. If any error occurs,
57 // returns false and outputs error message to standard error.
59 bool WriteFile(const char* filename, const char* mode, const T* data,
61 const bool use_stdout =
62 !filename || (filename[0] == '-' && filename[1] == '\0');
63 if (FILE* fp = (use_stdout ? stdout : fopen(filename, mode))) {
64 size_t written = fwrite(data, sizeof(T), count, fp);
65 if (count != written) {
66 fprintf(stderr, "error: could not write to file '%s'\n", filename);
69 if (!use_stdout) fclose(fp);
71 fprintf(stderr, "error: could not open file '%s'\n", filename);
77 #endif // LIBSPIRV_TOOLS_IO_H_