gpt4 book ai didi

c - 使用 read() 函数读取文件

转载 作者:太空狗 更新时间:2023-10-29 16:52:59 29 4
gpt4 key购买 nike

我必须编写一个程序来读取每行中的数字。是否可以只读取文件的一行,然后从缓冲区中读取 int,依此类推直到文件结束?很难找到使用读写的好例子。我的示例有点工作,但我想阅读直到它检测到 '\n' char,然后将 buffer 转换为 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);
}

最佳答案

逐字节读取并检查每个字节与'\n'是否一致,如果不是,则将其存储到buffer
如果是'\n' 添加'\0'到buffer中然后使用atoi()

你可以像这样读取一个字节

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

参见 read()

关于c - 使用 read() 函数读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19769542/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com