0

[C 平台] 我有一个文本文件和文本文件的第一行为“校准(版本 6.0.26.54947)”我需要忽略字符“校准(版本)”并只读取数字“6.0.26.54947”。

我有以下代码并继续......任何人都可以帮助我。

// open a file
pFile = fopen("text.txt", "r" );
if ( pFile == NULL ) {
    WriteToErrorWin("ERROR: Can not open the file!");
    return ( -1 );
}

// get a file size
fseek(pFile, 0 , SEEK_END);
lFileSize = ftell(pFile); 
rewind(pFile);

// allocate memory to contain the whole file:
szFile = (char*)calloc(lFileSize, sizeof(char));
if ( szFile == NULL ) {
    fclose(pFile);
    return ( -1 );
}

char *szFileLine_1 = szFile;   
if( fgets(szFileLine_1, lFileSize , pFile) == NULL ){
    return -1;
}
4

2 回答 2

1

这是您可以尝试的示例:

  char *text = "Calibrate (version 6.0.26.54947)";

  for (int i = 0; i < strlen(text); i++) {
    if (text[i] >= 46 && text[i] <= 57) {
      printf("%c", text[i]);
    } else {
      continue;
    }
  }

基于 ASCII 表:

在此处输入图像描述

输出:

6.0.26.54947
于 2020-05-20T09:14:24.827 回答
0

不建议使用fseek()andftell来获取文件大小,而是应该使用fstat()

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


int main()
{
    FILE* fp = NULL;    // setup fp

    struct stat statbuf;
    fstat(fileno(fp), &statbuf);

    long file_size = statbuf.st_size;
}

使用可以使用这样的功能来读取您感兴趣的字符

char* read_version(char* line, char* allow) // allow = "0123456789."
{
    char* re_result = malloc(strlen(line) + 1); // prepare for the edge case
    char* result = re_result;
    char tmp[2]; tmp[1] = '\0';
    for (; *line != '\0'; line++) {
        tmp[0] = *line;
        if (strstr(allow, tmp) != NULL) {
            *result = *line;
            result++;
        }
    }

    *result = '\0';

    return re_result;
}
于 2020-05-20T09:26:22.087 回答