如何从文件中获取一些值并将其存储到C中的数组中

时间:2017-04-24 15:26:01

标签: c

我正在尝试使用open / read系统调用从输入文件中获取一些值,如下所示:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <stddef.h>
    #include <semaphore.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <errno.h>

        #define BUFFER_SIZE 1024

        int main (int argc, const char * argv[] ){

        int inputFile;
        char buffer[BUFFER_SIZE];

        int heed;

        if (argc < 1){
            perror("There isn't any file");
            return -1;
        }
        else {
        input = open(argv[1], O_RDONLY);
        if (inputFile < 0){
            printf("Error, execution interrupted\n");
            return -1;
        }

        inputFile = open(datos,O_RDWR);
        while((heed = read(inputFile,buffer,BUFFER_SIZE)) != 0);
    printf("The first value stored in buffer is: %s\n",buffer[0]);
}
 return 0
 }

当我尝试打印存储在缓冲区中的值时,我得到的值与我写的不同。

The first value stored in buffer is: 52

输入文件包含这些值,用空格分隔:

4 5 5 2 1 2 3 3 5 2 

1 个答案:

答案 0 :(得分:0)

您可以像这样使用fscanf

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

#define BUFFER_SIZE 1024

int main(int argc, char *argv[]) {
  char buffer[BUFFER_SIZE];
  if(argc < 2) {
    fprintf(stderr, "Please provide file name\n");
    return EXIT_FAILURE;
  }
  FILE *pFile = fopen(argv[1], "r+");
  if(pFile == NULL) {
    fprintf(stderr, "No such file\n");
    return EXIT_FAILURE;
  }

  int nBufferLen = 0;
  while(nBufferLen < BUFFER_SIZE) {
    int nRet = fscanf(pFile, "%c", &buffer[nBufferLen]);
    if(nRet == EOF) break;
    else if(nRet == 1) { /* read successfully */ }
    else {
      printf("No Match\n");
    }
    nBufferLen++;
  }
  int i;
  for(i = 0; i < nBufferLen; i++)
    printf("%c ", buffer[i]);
  printf("\n");
  fclose(pFile);
  return 0;
}

当我运行它时,我可以看到所需的输出:

~/Documents/src : $ gcc arrayFile.c 
~/Documents/src : $ ./a.out stuff.txt 
4   5   5   2   1   2   3   3   5   2 

我希望这会有所帮助。