Reputation: 11
[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".
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;
}
Upvotes: 0
Views: 63
Reputation: 1829
Using fseek()
and ftell
to get the file size is not advisable, instead you should use 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
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;
}
Upvotes: 0
Reputation: 169
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:
Output:
6.0.26.54947
Upvotes: 1