gpt4 book ai didi

c - 使用 read() c 从文件中读取整数

转载 作者:行者123 更新时间:2023-11-30 17:18:53 25 4
gpt4 key购买 nike

我的文件 read() 函数有问题。我的文件是这样的:

4boat
5tiger
3end

其中数字是后面的字符串的长度。我需要使用低级 I/O 从输入文件读取整数和字符串并在 stdoutput 上打印它们。这是我的代码:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>

int main(int argc, char *argv[]){
int *len, fd, r_l, r_s;
char *s;
fd=open(argv[1], O_RDONLY);
if(fd>=0){
do{
r_l=read(fd, len, sizeof(int));
r_s=read(fd, s, (*len)*sizeof(char));
if(r_l>=0){
write(1, len, sizeof(int));
write(1, " ",sizeof(char));
}
if(r_s>=0)
write(1, s, (*len)*sizeof(char));
}while(r_l>=0 && r_s>=0);
}
return 0;
}

但它不起作用=/

最佳答案

您没有为 poitner len 分配空间,您需要为其分配空间,只需将其声明为 int len; 即可,这样它就得到了在堆栈中分配,您不需要手动处理它的分配,所以它会是这样的

int main(void) {
int len, fd, r_l, r_s;
char *s;
fd = open(argv[1], O_RDONLY);
if (fd >= 0) {
do {
r_l = read(fd, &len, sizeof(int));
s = malloc(len); /* <--- allocate space for `s' */
r_s = 0;
if (s != NULL)
r_s = read(fd, s, len);
if (r_l >= 0) {
write(1, &len, sizeof(int));
write(1, " ", 1);
}
if ((r_s >= 0) && (s != NULL))
write(1, s, len);
free(s);
} while (r_l >= 0 && r_s >= 0);
close(fd);
}
return 0;
}

您也没有为 s 分配空间,这是另一个问题,我确实使用 malloc() 在上面更正的代码中为 s 分配了空间.

根据定义,sizeof(char) == 1,所以你不需要它。

虽然上面的代码不会出现您的代码所具有的错误,即调用未定义的行为,但它不会执行您期望的操作,因为无法使用此算法读取您的数据。

文件中的数字并不是真正的整数,它们是字符,所以你真正需要的是这个

int main(void) {
char chr;
int len, fd, r_l, r_s;
char *s;
fd = open(argv[1], O_RDONLY);
if (fd >= 0) {
do {
r_l = read(fd, &chr, 1);
len = chr - '0';
s = malloc(len); /* <--- allocate space for `s' */
r_s = 0;
if (s != NULL)
r_s = read(fd, s, len);
if (r_l >= 0) {
printf("%d ", len);
}
if ((r_s >= 0) && (s != NULL))
write(1, s, len);
free(s);
} while (r_l >= 0 && r_s >= 0);
close(fd);
}
return 0;
}

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

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