rbuf从文件中读取数据,但无法将其传输到数组

时间:2015-04-16 10:47:42

标签: c system-calls

所以我有一个编译的readNumbers函数,该函数应该从输入文件中读取数字,而rbuf缓冲区则读取要传输到数组的文件位。但是,当我给它一个输入时,比方说, 12 3 5 6 7 34 11, 它只是从文件中读取一个字符,然后将其他所有字符设置为0并完成。

int readNumbers(int **array, char* fname) {

    char *errmsg = "Failed to open input file!\n";
    char rbuf[16];
    int numberRead = 0, numberAllocated = 2, fd;
    int temp = 0, i = 0;
    int nRead = 0, negative = 1;
    int newNumber = 0;

    *array = (int *)malloc(numberAllocated * sizeof(int));

    fd = open(fname, O_RDONLY, 0);
    if (fd == -1){

        write(2, errmsg, 31);
        return (-1);
    }

    while ((nRead = read(fd, rbuf, 16)!=0)){
        for (i = 0; i < 16; i++){
            printf("%d, ", rbuf[i]);
        }
        printf("\n");
        for (i = 0; i < nRead; i++){
            printf("A, %d\n", nRead);
            if (numberRead == numberAllocated){
                numberAllocated *= 2;
                *array = (int *)realloc(*array, numberAllocated * sizeof(int));
            }

            if (rbuf[i] == '-'){
                negative = (-1);
            }
            else if (isdigit(rbuf[i])){
                printf("B");
                if (newNumber == 0){
                    printf("C\n");
                    temp = rbuf[i] - '0';
                    printf("%d\n", temp);
                    newNumber = 1;
                }
                else{
                    printf("D");
                    temp *= 10;
                    temp += (rbuf[i] - '0');
                }
            }
            else{
                printf("E");
                if (newNumber == 1){
                    temp *= negative;
                    *array[i] = temp;
                    negative = 1;
                    temp = 0;
                    newNumber = 0;
                    numberRead ++;
                }
            }
        }
        for (i = 0; i < 16; i++){
            rbuf[i] = '\0';
        }
    }

    close(fd);

    return numberRead;
}

有什么想法吗?感觉问题与read()nRead有关,但我无法弄清楚它是什么。

目前的输出是:     49,50,32,51,10,53,32,54,32,55,10,51,52,32,49,49;     A,1;     公元前;     1;

2 个答案:

答案 0 :(得分:1)

结果很容易解决这个问题。

while ((nRead = read(fd, rbuf, 16)!=0)){

所以,如果仔细观察,你会发现这里的括号出现了问题。正确的格式是这样的:

while ((nRead = read(fd, rbuf, 16))!=0){

所以是的。基本上它是检查实际读取的字符数是否为零,然后将该真值分配给用于保存字符数的变量。

答案 1 :(得分:0)

您应该在此部分

之前将i计数器初始化为0
if (rbuf[i] == '-'){
    negative = (-1);
  }
  else if (isdigit(rbuf[i])){
    printf("B");
    if (newNumber == 0){
      printf("C\n");
      temp = rbuf[i] - '0';
      printf("%d\n", temp);
      newNumber = 1;
    } 
    else{
      printf("D");
      temp *= 10;
      temp += (rbuf[i] - '0');
    }
  }
  else{
    printf("E");
    if (newNumber == 1){
      temp *= negative;
      *array[i] = temp;
      negative = 1;
      temp = 0;
      newNumber = 0;
      numberRead ++;
    }
  }