繁体   English   中英

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

[英]read integer from file with read() c

我对文件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 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM