简体   繁体   English

如何读取和打印issuance.csv数据结尾?

[英]How to read and print end of data issuance.csv file?

I need to read data store in end of file and print it. 我需要读取文件末尾的数据存储并进行打印。 My input file has many numbers, and I have to read last number, can any one help me?? 我的输入文件有很多数字,我必须阅读最后一个数字,有人可以帮忙吗?

int main()
{
    FILE *fp;
        fp = fopen("f:\\Issuance.csv", "a");
        if (!fp)
        {
            printf("can not open file \n");
            getchar();
            exit(1);
        }
        int Size = 30;
        char FileInfo[100];
                fseek( fp , 0 , SEEK_END);
                fread(FileInfo, 1, Size, fp);
                printf("%d",FileInfo);
}
fcloseall();
            }

You need to use the 2nd parameter of fseek() . 您需要使用fseek()的第二个参数。

fseek(fp, -Size, SEEK_END);
fread(FileInfo, 1, Size, fp);
FileInfo[Size] = '\0'; // NULL terminate FileInfo; or declare as char FileInfo[100] = {0};
printf("%s", FileInfo);

To read the last number in a text file (which may have additional junk after it), starting from the beginning, attempt to read a number. 要从头开始读取文本文件中的最后一个数字(其后可能还有其他垃圾),请尝试读取一个数字。 If successful, save it, else toss 1 char . 如果成功,保存它,否则扔1个char Continue until the end of the file. 继续直到文件末尾。

// Read last number
int ReadLastNumber(FILE *inf, int default_value) {
  int last = default_value;
  int num;
  int cnt;
  rewind(inf);
  while ((cnt = fscanf(inf,"%d", &num)) != EOF) {
    if (cnt == 1) {
      last = num;
    } else {
      fgetc(inf);  // toss non-numeric char
    }
  }
  return last;
}

A more sane solution would fseek() to the end, search backwards for digits. 更为合理的解决方案将是fseek()到最后,向后搜索数字。 Once some digits are found, continue backwards looking for digits, + or - . 找到一些数字后,继续向后寻找数字+- Something like the following untested code. 类似于以下未经测试的代码。

#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>

// Read last number
int ReadLastNumber2(FILE *inf, int default_value) {
  int last = 0;
  int place = 1;
  bool digit_found = false;
  long offset = -1;
  while (fseek(inf, offset, SEEK_CUR) == 0) {
    int ch = fgetc(inf);
    if (ch == EOF)  // Likely I/O error
      return default_value;
    if (isdigit(ch)) {
      digit_found = true;
      last += (ch - '0')*place;
      place *= 10;
      offset = -2;
    } else if (ch == '-') {
      return -last;
    } else if (digit_found) {
      return last;
    }
  }
  return default_value;
}

Not protected against int overflow. 无法防止int溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM