简体   繁体   English

尝试从读取的文本文件中仅删除第一行中的字符

[英]Try to remove only character in first line from read text File

[C Platform] i have a text file and first line of the text file as "Calibrate (version 6.0.26.54947)" i need to ignore the characters "Calibrate (version )" and read only the number "6.0.26.54947". [C 平台] 我有一个文本文件和文本文件的第一行为“校准(版本 6.0.26.54947)”我需要忽略字符“校准(版本)”并只读取数字“6.0.26.54947”。

i have following code and struck to continue.. could any one help me.我有以下代码并继续......任何人都可以帮助我。

// 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;
}

Here is an example you can try:这是您可以尝试的示例:

  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;
    }
  }

Based on the ASCII table:基于 ASCII 表:

在此处输入图像描述

Output: Output:

6.0.26.54947

Using fseek() and ftell to get the file size is not advisable, instead you should use fstat()不建议使用fseek()ftell获取文件大小,而应使用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;
}

Use can use a function like this to read the characters you are interested in使用可以像这样使用 function 来读取您感兴趣的字符

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;
}

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

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