read()関数でファイルから読み込む
数字を1行ずつ区切って読み込むプログラムを書かなければなりません。ファイルの1行だけを読んで、次にバッファからint
を読み、それをファイルの終わりまで続けることは可能でしょうか?readとwriteを使った良い例を見つけるのは本当に難しいです。 私の例は一応動いているのですが、`'charを検出するまで読み、その後バッファを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]);
}
コードを修正しました:
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);
}
9
2
Byteずつ読んで、各Byteが
' \n'
と一致するかチェックし、一致しない場合はbuffer
に格納します。このように1バイトを読み込むことができます。
参照
read()
。fgetsはあなたのために働くでしょう。これに関する非常に良いドキュメントがあります :-
http://www.cplusplus.com/reference/cstdio/fgets/
もし、fgetsを使いたくないのであれば、以下の方法が有効です。