簡體   English   中英

如何使用自定義fget從CSV文件獲取行

[英]How to get a line from csv file with a custom fgets

我目前正在用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM