* New version 2.26
[alpine.git] / pith / readfile.c
blob02ba54aa0311620b8efd9a5e245652b15afb1d43
1 /*
2 * ========================================================================
3 * Copyright 2013-2022 Eduardo Chappa
4 * Copyright 2006 University of Washington
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * ========================================================================
15 #include "../pith/headers.h"
17 #include "../pith/store.h"
19 #include "readfile.h"
22 /*----------------------------------------------------------------------
23 Read whole file into memory
25 Args: filename -- path name of file to read
27 Result: Returns pointer to malloced memory with the contents of the file
28 or NULL
30 This won't work very well if the file has NULLs in it.
31 ----*/
32 char *
33 read_file(char *filename, int so_get_flags)
35 STORE_S *in_file = NULL, *out_store = NULL;
36 unsigned char c;
37 char *return_text = NULL;
39 if((in_file = so_get(FileStar, filename, so_get_flags | READ_ACCESS))){
42 if(!(out_store = so_get(CharStar, NULL, EDIT_ACCESS))){
43 so_give(&in_file);
44 return NULL;
48 * We're just using the READ_FROM_LOCALE flag to translate
49 * to UTF-8.
51 while(so_readc(&c, in_file))
52 so_writec(c, out_store);
54 if(in_file)
55 so_give(&in_file);
57 if(out_store){
58 return_text = (char *) so_text(out_store);
59 /* avoid freeing this */
60 if(out_store->txt)
61 out_store->txt = NULL;
63 so_give(&out_store);
67 return(return_text);
70 /* our copy, to_file and from_file must be full paths. from_file
71 * must exist.
73 int
74 our_copy(char *to_file, char *from_file)
76 STORE_S *in_cert, *out_cert;
77 unsigned char c;
79 in_cert = so_get(FileStar, from_file, READ_ACCESS | READ_FROM_LOCALE);
80 if (in_cert == NULL)
81 return -1;
83 out_cert = so_get(FileStar, to_file, WRITE_ACCESS | WRITE_TO_LOCALE);
84 if (out_cert == NULL){
85 so_give(&in_cert);
86 return -1;
89 so_seek(out_cert, 0L, 0);
90 so_truncate(out_cert, 0);
92 while(so_readc(&c, in_cert) > 0)
93 so_writec(c, out_cert);
95 so_give(&in_cert);
96 so_give(&out_cert);
98 return 0;