Line data Source code
1 : /*!
2 : * \file
3 : * \author Christopher Stender
4 : * \date 2018-02-15
5 : * \version 0.1
6 : *
7 : * \brief Read or write a fixed number of bytes
8 : *
9 : * \details
10 : * Use read_n() to read or write_n() to write a fixed number of bytes from or
11 : * to a file descriptor.
12 : *
13 : *\copyright
14 : * Copyright (c) 2023 Fraunhofer IIS
15 : *
16 : * Permission is hereby granted, free of charge, to any person obtaining a copy
17 : * of this software and associated documentation files (the “Software”), to deal
18 : * in the Software without restriction, including without limitation the rights
19 : * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20 : * copies of the Software, and to permit persons to whom the Software is
21 : * furnished to do so, subject to the following conditions:
22 : *
23 : * The above copyright notice and this permission notice shall be included in
24 : * all copies or substantial portions of the Software.
25 : *
26 : * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 : * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 : * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29 : * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 : * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31 : * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 : * THE SOFTWARE.
33 : */
34 :
35 : #include <unistd.h>
36 :
37 : #include "rw_n.h"
38 :
39 0 : int read_n(int fd, void* buf, size_t count)
40 : {
41 : int bytes_read;
42 0 : int to_read = count;
43 0 : uint8_t* buffer = (uint8_t*)buf;
44 :
45 0 : while(to_read > 0) {
46 0 : bytes_read = read(fd, buffer, to_read);
47 0 : if(bytes_read <= 0)
48 0 : return bytes_read;
49 :
50 0 : buffer += bytes_read;
51 0 : to_read -= bytes_read;
52 : }
53 :
54 0 : return count;
55 : }
56 :
57 0 : int write_n(int fd, const void* buf, size_t count)
58 : {
59 : int bytes_written;
60 0 : int to_send = count;
61 0 : uint8_t* buffer = (uint8_t*)buf;
62 :
63 0 : while(to_send > 0) {
64 0 : bytes_written = write(fd, buffer, to_send);
65 0 : if(bytes_written <= 0)
66 0 : return bytes_written;
67 :
68 0 : buffer += bytes_written;
69 0 : to_send -= bytes_written;
70 : }
71 :
72 0 : return count;
73 : }
|