如何使用自定义FGET从csv文件中获取行

如何使用自定义FGET从csv文件中获取行,c,csv,C,Csv,我目前正在用C编写一个程序,从CSV文件中读取,我有一个定义的缓冲区大小,但在将每一行从缓冲区中分离出来时遇到了问题。通过检查'\n'字符,我可以看到行的结尾。但是,我无法从缓冲区中提取该行进行解析。有人有什么想法吗 #ifndef BUFFSIZE #define BUFFSIZE 4096 #endif int main() { int fd; int fdBin; char * buf = malloc(BUFFSIZE); int count = 0; bo

我目前正在用C编写一个程序,从CSV文件中读取,我有一个定义的缓冲区大小,但在将每一行从缓冲区中分离出来时遇到了问题。通过检查'\n'字符,我可以看到行的结尾。但是,我无法从缓冲区中提取该行进行解析。有人有什么想法吗

#ifndef BUFFSIZE
   #define BUFFSIZE 4096
#endif

int main() {
  int fd;
  int fdBin;
  char * buf = malloc(BUFFSIZE);
  int count = 0;

  bool EOFFlag = false;

  fd = open("SongCSV.csv", O_RDONLY);
  fdBin = open("BinarySongData.bin", O_CREAT | O_WRONLY, "0600");
  if (fd == -1) {
    printf("failed to open a file\n");
    exit(1);
  }

  off_t offset = 0;
  off_t offsetOld = 0;

  int readBytes;

  while (!EOFFlag) {
    offsetOld = offset;
    offset = lseek(fd, offset - offsetOld, SEEK_CUR);

    readBytes = read(fd, buf, BUFFSIZE);

    printf("\n\n%lld\n\n", (offset));
    int i = 0;
    int commaCounter = 0;
    while (i < readBytes) {
      if (buf[i] != '\n') {

      }

      if (buf[i] == '\n') {
        printf("\t\t THIS IS END OF LINE \t%d", i);
        commaCounter = 0;

      }

      if (buf[i] == ',') {
        commaCounter++;
        if (commaCounter == 4) {
          printf("****Album Name****");
        }
      }
      write(fdBin, buf, BUFFSIZE);
      printf("%c", buf[i]);
      i++;
    }
    if (readBytes < BUFFSIZE) {
      EOFFlag = true;
      printf("\nREACHED END OF FILE");
    }
    printf("\n");
    printf("AA: END OF LINE ****%d*****", count);

    count++;
  }

  close(fd);
  close(fdBin);
  return 0;
}

我这样做,简单易行。我只是做得很快,任何疑问都可以问我,干杯

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
  int len = sending();
  char *firstline;
  int i = 0;
  char buf[0];
  int rd ;
  int fd = open("hey.csv", O_RDONLY);

  rd = read(fd, buf, 1);    
  firstline = malloc(sizeof(char) * len);
  while (i != len)
    {
      firstline[i] = buf[0];
      i++;
      rd = read(fd, buf, 1);
    }
  firstline[i] = '\0';
  printf("%s\n", firstline);
  return (0);
}

int sending()
{
  int fd = open("hey.csv", O_RDONLY);
  char buf[1];
  int r = 0;
  r = read(fd, buf, 1);
  int len = 0;

  while (buf[0] != '\n')//getting exact size to malloc
    {
      len++;
      r = read(fd, buf, 1);    

    }
  return len;
}

为什么不使用fopen和fgets?我在学校的作业禁止使用“F”功能。你不认为在你的问题中提到这一点很重要吗?是的,我现在要编辑它。你到底想做什么?为什么每次迭代都要将缓冲区写入输出文件?CSV只是一行还是必须从多行中选择一行?