For starters, you need to format your code properly, e.g.,
Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
int main(void) {
FILE *fp = fopen("file.txt","r");
//first wanted to get the number of lines
size_t nbytes;
ssize_t read;
char *my_string;
int fr = 0;
while ((read = getline(&my_string, &nbytes, fp)) != -1) {
four++;
}
printf("this is the number of lines in the given file : %d \n", fr);
fclose(fp);
my_string = (char *)malloc(fr);
//here I open the file again for my calculations
FILE *fpp = fopen("file.txt", "r");
int ii = 0;
double *s;
s = (double *)malloc(fr);
while ((read = getline(&my_string, &nbytes, fpp)) != -1) {
my_string[strlen(my_string) - 1] = 0;
s[ii] = atof(my_string);
ii++;
}
fclose(fpp);
free(my_string);
return 0;
}
I presume that the instance of the usage of an undeclared variable named four should actually be fr, and that the variable named fr would have been more descriptively named line_count.
Next, I presume that the getline function used here is the non-standard yet POSIX standard getline. If so, your usage of it is incorrect:
Code:
while ((read = getline(&my_string, &nbytes, fp)) != -1) {
Here's what my manual says:
Code:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.)
Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.
You passed a pointer to my_string to getline, but my_string is a pointer that was not initialised. As above, this is a mistake: either my_string is a null pointer, or my_string points to a malloc-allocated buffer of the corresponding size. In this case, it seems that you want the former since you don't know how long is the first line, so fix by initialising my_string to be a null pointer.
After doing this fix, it looks like you have a strange malloc here:
Code:
my_string = (char *)malloc(fr);
fr is the number of lines in the file, so why do you have this malloc? You only need it for s (which frankly is a poor name: s should have been named numbers, or something even more descriptive).
Finally, you should remember to free(s) after you are done with it, though presumably you will be doing something with s so you're not actually done with it just yet.
Oh, and remember to check that malloc does not return a null pointer, and likewise fopen.