簡體   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