【问题标题】:read integer from file with read() c使用 read() c 从文件中读取整数
【发布时间】:2015-03-14 13:15:22
【问题描述】:

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

4boat
5tiger
3end

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

#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;
}

但它不起作用=/

【问题讨论】:

  • 一个问题是前导数字实际上不是数字,它是一个字符,它是一个字节(sizeof(int) 通常是 4 个字节)。
  • 会有比 9 更长的字符串吗?
  • 如何为 len(在 read() 中用于缓冲区)和 s(在 read() 中也用作缓冲区)分配存储空间。

标签: c file integer posix


【解决方案1】:

您没有为 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;
}

【讨论】:

  • 必须检查 malloc 我们是否成功。即使只是简单地写s = xmalloc(len) 并省略xmalloc 的定义就足够了。
  • @WilliamPursell 我正在检查 malloc 是否成功,你看不到吗?所有的标题都包含在 OP 的程序中。你从哪里带来xmalloc()?如果malloc() 失败,我的程序不会表现不佳,我很确定。
  • 另外读取 1 个字节到 &amp;len 点可能会失败,具体取决于系统的字节序。去使用char
  • @alk 再次正确 lenint 并且代码以任何方式使其其余部分未初始化。
  • 你应该分享你对我帮助很大的-1,你想要-0.5吗? ;-)
猜你喜欢
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
相关资源
最近更新 更多