I am trying to read elements in a function and store them in an array in main. I use a pointer to a dynamic array, but its not working. The address i get when i deference the pointer is NULL and the program crashes.
Here is the array :
char* first_name = malloc(first_name_length*sizeof(char));
Function call from main:
get_first_name(fp, first_name_length, first_name);
Function declaration:
void get_first_name(FILE* fp, int length,char* first);
Function definition:
void get_first_name(FILE* fp, int length, char* first){
char c;
int i = 0;
int number_of_conversions;
number_of_conversions = fscanf(fp, "%c", &c);
while (!isspace(c)){
first[i] = c;
number_of_conversions = fscanf(fp, "%c", &c);
i++;
}
}
something like the following will do the job
void get_first_name(FILE* fp, int length, char* first)
{
int c;
int i = 0;
while ( EOF != (c = fgetc(fp) ) && (' ' != c) && (i < (length -1)) )
{
first[i] = c;
i++;
}
// terminate the string
first[i] = '\0';
}
fp = fopen ( "file.txt", "r"));
Make sure file is not Empty. using fgetc() will help keeping it simple.
void get_first_name(FILE* fp, int length, char* first)
{
char c;
int i = 0;
c=fgetc(fp);
while (c!=EOF && !isspace(c) ){
first[i] = c;
c=fgetc(fp);
i++;
}}
3 . If you are using fscanf() for some purpose , you can use fseek() for checking if the file is Empty or not.
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.