这是一个使用 malloc() 和 free() 的版本。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* "user " */
#define USERLINE_PREFIX 5
/* "password " */
#define PASSLINE_PREFIX 9
void set_credentials(char**, char**);
int main(void)
{
/* to point to the username and password obtained from a text file */
char *username = NULL;
char *password = NULL;
set_credentials(&username,&password);
/* (original scheme) printf("username: %s\n", username); */
/* (original scheme) printf("password: %s\n", password); */
printf("username: %s\n", username + USERLINE_PREFIX ); // line starts "user "
printf("password: %s\n", password + PASSLINE_PREFIX ); // line starts "password "
/* (original scheme) free(username - USERLINE_PREFIX); */
/* (original scheme) free(password - PASSLINE_PREFIX); */
free(password);
free(username);
return EXIT_SUCCESS;
}
void set_credentials(char **username, char **password)
{
/* file format:
line 1 ->user <username>
line 2 ->password <password>
*/
char c;
#define FILE_LINES 2
#define MAX_LINE_LENGTH 100
int i = 0, j = 0;
char *lines[FILE_LINES];
char *tmp = NULL;
char *user = "user ";
char *pass = "password ";
char user_found = 0, password_found = 0;
for (j = 0; j < FILE_LINES; j++)
{
lines[j] = malloc( MAX_LINE_LENGTH + 1 );
lines[j][0] = '\0';
}
tmp = lines[0];
const char *filename = "/netnfork/config/netnfork_credentials.properties";
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("ERROR %d trying to open %s\n",errno,filename);
/* if not exiting program, would need to free() here */
exit(EIO);
}
/* in case more lines than expected */
while ((c = fgetc(fp)) != EOF && i < FILE_LINES)
{
if (c != '\n')
{
*tmp = c;
tmp++;
} else {
*tmp = '\0';
i++;
tmp = lines[i];
}
}
if ( i < 2 ) {
printf("ERROR: file %s is incomplete needs %d lines (password and user)\n",filename,FILE_LINES);
/* if not exiting program, would need to free() here */
exit(1);
}
fclose(fp);
i = 0;
while (i < FILE_LINES)
{
if (strncmp(user, lines[i], USERLINE_PREFIX) == 0)
{
user_found = 1;
/* (original scheme) *username = lines[i] + USERLINE_PREFIX; */
*username = lines[i];
}
else if ( strncmp (pass, lines[i],PASSLINE_PREFIX) == 0 ) {
password_found = 1;
/* (original scheme) *password = lines[i] + PASSLINE_PREFIX; */
*password = lines[i];
}
else {
printf("ERROR: invalid line in file:\n");
printf("%s\n",lines[i]);
/* if not exiting program, would need to free() here */
exit(1);
}
i++;
}
/* check for the extremely unlikely event that the two lines are both of the same type */
if ( ! (password_found && user_found ) )
{
printf("ERROR: file %s is invalid, missing %s line\n",filename, (user_found) ? "password" : "user" );
/* if not exiting program, would need to free() here */
exit(1);
}
}