Reputation: 1827
I can't seem to work it out. I am using a .c code that opens a file and reads each line. I would like to save in char*substr 4 characters from the line 9 inside the txt file. The line 5 contains name=Me She; I would like to have in char*substr just Meli.Need help. THX Here is the c code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
char str[128];
char str1[128];
if((fp = fopen("/home/folder/file.txt", "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
int lin=0;
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
if (lin==8)
{
char *c= (char *) malloc(sizeof(char)*strlen(str)+1);
c= strndup(str, strlen(str)-5);?? not working?!!!
printf("d is:",c);
}
lin=lin+1;
}
fclose(fp);
return 0;
}
Upvotes: 1
Views: 207
Reputation: 399793
You're calling malloc()
and then directly overwriting its result with that of calling strndup()
, this leaks memory.
Also, the logic in the strndup()
call looks wrong. If you want to skip the first 5 characters, you should have str + 5
.
If you have strdup()
, use:
if (lin==9)
{
char *name = strdup(str + 5);
printf("name is: '%s'\n", name != NULL ? name : "(failed)");
}
Then you should probably break
out of the loop. Also note that the pointer name
goes out of scope, so it's not available to code outside the loop for instance.
Upvotes: 0
Reputation: 5456
Your printf is wrong. change it to printf("d is %s\n",c);
.
By the way, strdup
allocate the memory needed, so you don't have to allocate it yourself. (In fact, you have a memory leak).
Upvotes: 1