Reading from a file using the read () function

I need to write a program that reads numbers on separate lines each. Is it possible to read only one line of the file, and then read int from the buffer and so on to the end of the file? It is very difficult to find good examples of the use of reading and writing. My example works, but I would like to read until it detects a '\n' char, and then converts the buffer to int.

 #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <iostream> int fd[2]; void readFile(int fd) { unsigned char buffer[10]; int bytes_read; int k=0; do { bytes_read = read(fd, buffer, 10); k++; for(int i=0; i<10; i++) { printf("%c", buffer[i]); } } while (bytes_read != 0); } int tab[50]; int main(int argc, char *argv[]) { if(argv[1] == NULL || argv[2] == NULL) { printf("Function requires two arguments!\nGood bye...\n"); return -1; } else { if (access(argv[1], F_OK) == 0) { fd[0] = open(argv[1], O_RDONLY); } else { fd[0] = open(argv[1], O_WRONLY|O_CREAT|O_SYNC, 0700); const int size = 50; for(int i=0; i<size; i++) { char buf[10]; sprintf(buf, "%d\n", i+1); write(fd[0], buf, strlen(buf)); } close(fd[0]); fd[0] = open(argv[1], O_RDONLY); if (access(argv[2], F_OK) == 0) fd[1] = open(argv[2], O_WRONLY); else fd[1] = open(argv[2], O_WRONLY|O_CREAT, 0700); } } if (access(argv[2], F_OK) == 0) fd[1] = open(argv[2], O_WRONLY); else fd[1] = open(argv[2], O_WRONLY|O_CREAT, 0700); readFile(fd[0]); close(fd[0]); close(fd[1]); } 

Revised Code:

 void readFile(int fd) { char buffer[10]; int bytes_read; int k = 0; do { char t = 0; bytes_read = read(fd, &t, 1); buffer[k++] = t; printf("%c", t); if(t == '\n' && t == '\0') { printf("%d", atoi(buffer)); for(int i=0; i<10; i++) buffer[i]='\0'; k = 0; } } while (bytes_read != 0); } 
+6
source share
2 answers

Read byte by byte and make sure that each byte is opposite '\n' if it is missing, then save it in buffer
if '\n' add '\0' to the buffer, then use atoi()

You can read one byte like this

 char c; read(fd,&c,1); 

See read()

+9
source

fgets will work for you. here is very good documentation on this: -
http://www.cplusplus.com/reference/cstdio/fgets/

If you do not want to use fgets, the following method will work for you: -

 int readline(FILE *f, char *buffer, size_t len) { char c; int i; memset(buffer, 0, len); for (i = 0; i < len; i++) { int c = fgetc(f); if (!feof(f)) { if (c == '\r') buffer[i] = 0; else if (c == '\n') { buffer[i] = 0; return i+1; } else buffer[i] = c; } else { //fprintf(stderr, "read_line(): recv returned %d\n", c); return -1; } } return -1; } 
0
source

Source: https://habr.com/ru/post/957343/


All Articles