pproctor
pproctor

Reputation: 101

Copying a desired string from a text file in C

I have read all the text from a desired file and it is now stored in buff. I want to copy just the string content after identifier strings such as 'Title'.

Example file below:

"Title: I$_D$-V$_{DS}$ Characteristic Curves (Device 1)
MDate: 2016-03-01
XLabel: Drain voltage V$_{DS}$
YLabel: Drain current I$_D$
CLabel: V$_{GS}$
XUnit: V
... "

for(;;) {
    size_t n = fread(buff, 1 , DATAHOLD, inFile);

    subString = strstr( buff, "Title");

        if( subString != NULL) {   
            strcpy(graph1.title , (subString + 7));
            subString = NULL;
        }

       ....more if statements....

        if( n < DATAHOLD) {
            break;
        }
}

I understand that strstr() returns a pointer to location of the search string, I added 7 to get just the text that comes after the search string and this part works fine. The problem is strcpy() copies the rest of buff character array into graph1.title. How to instruct strcpy() to only copy the text on the same line as the substring pointer? Using strtok() maybe?

Upvotes: 0

Views: 2274

Answers (3)

J...S
J...S

Reputation: 5207

I agree with ChuckCottrill, it would be better if you read and process one line at a time.

Also since the file you are dealing with is a text file, you could be opening it in text mode.

FILE *fin = fopen("filename", "r");

Read a line with fgets() into a string str. It should be noted that fgets() will take the trailing \n' to str.

fgets(str, sizeof(str), fin);

char *substring;
if( (substring = strstr(str, "Title: ")) != NULL )
{
    strcpy(graph1.title, substring+strlen("Title: "));
}

At this point, graph1.title will have I$_D$-V$_{DS}$ Characteristic Curves (Device 1) in it.

Upvotes: 2

ContinuousLoad
ContinuousLoad

Reputation: 4922

You could use another strstr to get the position of the end of the line, and then use strncpy which is like strcpy, but accepts a third argument, the number of chars to copy of the input.

Upvotes: 1

ChuckCottrill
ChuckCottrill

Reputation: 4444

Read and process a single line at a time.

for( ; fgets(line,...); ) {
    do stuff on line
}

Upvotes: 1

Related Questions