The following is a function that reads a file user.dat (attached after the code) and extracts a string and an int value delimited by ", " and "\\n" respectively.
void getUsers()
{
int i, t;
char *token1, *u;
FILE *fu = fopen("user.dat", "r");
const char s[2] = ", ";
if(fu != NULL)
{
char line1[20];
while(fgets(line1, sizeof line1, fu) != NULL)
{
token1 = strtok(line1, s);
for(i=0;i<2;i++)
{
if(i==0)
{
u = token1;
token1 = strtok(NULL,s);
} else {
t=atoi(token1);
}
}
addOuterNode(u,t);
}
printOuterNode();
fclose(fu);
} else {
perror("user.dat");
}
}
The user.dat file is as follows:
1000, 76
0095, 81
2910, 178
0001, 1
<EOF>
The program works fine if the above format is maintained.
However I run into problems (SIGSEGV generally as the *u and t values are sent to a function that inserts them into void * data elements in nodes of a linked list/nested linked list) when there are stray spaces or newlines in the file. Eg:
<newline>
1000, 76
<space>
0095, 81
2910, 178
0001, 1
<space><newline>
<newline>
<EOF>
Would you be able to help me to preprocess the user.dat textfile so that I can remove the unwanted whitespace characters?
You can preprocess a file to exclude lines containing only whitespace characters. Eg in Perl this would be: perl -ne "print if !/^\\s*$/" input.txt > output.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.