| |

VerySource

 Forgot password?
 Register
Search
View: 977|Reply: 3

A question about file pointers in Linux?

[Copy link]

3

Threads

4

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-2-7 20:30:01
| Show all posts |Read mode
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int Get_Config (char * lpFileName, char * SerchBuf, char * szTmp)
{
    FILE * stream;
    char pBuf [256] = "";
    char * p;
    char * ptoken = NULL;
    
   if ((stream = fopen (lpFileName, "rt")) == NULL)
{
printf ("opne file is error\n");
        return -1;
}
while (! feof (stream))
{
memset (pBuf, 0x00, 256);
fgets (pBuf, 256, stream);
if (strstr (pBuf, SerchBuf))
{
p = strchr (pBuf, '=');
strncpy (szTmp, p + 1, sizeof (pBuf));
printf ("this is very important data% s\n", szTmp);
break;
}
else
continue;
    }
    fclose (stream);
    return 1;
}


int main ()
{
    char lpFileName [128] = "Config.ini";
    char szTmp [128];
    
    memset (szTmp, 0x00, 128);
    if (Get_Config (lpFileName, "TMP_LEN =", szTmp) ==-1)
    {
       printf ("get config error\n");
    }
    printf ("this TMP_LEN is% s\n", szTmp);
Ranch
   getchar ();
    return 0;
}

When I execute this program, I can correctly read the contents of the configuration file once, but the second time I call the Get_Config function above, the lpFileName file cannot be opened normally. Excuse me, what went wrong there, I have been looking for a long time and still have no clue.
Reply

Use magic Report

0

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 France

Post time: 2020-8-9 20:15:01
| Show all posts
Did you make the second call there
Reply

Use magic Report

0

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-8-10 20:15:01
| Show all posts
Is the file not closed yet? Calling it in main after the call is complete will risk the mistake you said
Reply

Use magic Report

0

Threads

12

Posts

9.00

Credits

Newbie

Rank: 1

Credits
9.00

 Invalid IP Address

Post time: 2020-8-11 22:30:01
| Show all posts
The problem lies in your strncpy, this function in linux will initialize dest with 0, the length is the third parameter of strncpy, and the parameter you give is obviously larger than the size of dest, so unpredictable things happen ...
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list