Your use of &somePointer
in both locations in this code is wrong. The result of &somePointer
is char**
. When applying the unary address-of operator &
, the result is pointer-to-type. Since somePointer
is a char*
, that means &somePointer
is a char**
, which is not what you want. It is wrong usage of the %s
format specifier using scanf
and likewise for printf
.
Both of those functions require an address of a char
buffer, not the address of a char
pointer. While you may think just using somePointer
will work, in fact it will not, as even then that variable is indeterminate. You never provide the pointer with a valid address where a char
buffer resides.
And, your while-loop logic is wrong. it is equivalent to a while(!feof(filePointer))
loop, which is nearly-always wrong. You can read more about it here
The following is a simple slab of code that safely reads strings up to 127 chars wide from a file until the file is exhausted or an error is encountered:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buff[128];
FILE *fp = fopen("data2.txt","r");
if (fp == NULL)
{
perror("data2.txt");
return EXIT_FAILURE;
}
while (fscanf(fp, "%127s", buff) == 1)
{
printf("String from file: %s\n", buff);
}
fclose(fp);
return 0;
}
Adding a pointer to this gives the slightly modified:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buff[128];
char *somePointer = buff;
FILE *fp = fopen("data2.txt","r");
if (fp == NULL)
{
perror("data2.txt");
return EXIT_FAILURE;
}
while (fscanf(fp, "%127s", somePointer) == 1)
{
printf("String from file: %s\n", somePointer);
}
fclose(fp);
return 0;
}
Next, dynamic allocation instead of a fixed automatic buffer. That gives us:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *somePointer = malloc(128);
if (somePointer == NULL)
{
perror("Failed to allocate buffer space");
return EXIT_FAILURE;
}
FILE *fp = fopen("data2.txt","r");
if (fp == NULL)
{
perror("data2.txt");
return EXIT_FAILURE;
}
while (fscanf(fp, "%127s", somePointer) == 1)
{
printf("String from file: %s\n", somePointer);
}
fclose(fp);
free(somePointer);
return 0;
}
In each case above, the argument passed to fscanf
and printf
is ultimately a pointer-to-char. the first is done by conversion, the latter two explicitly. Which of these applies to your usage needs I leave to you.
The rest I leave to you. Best of luck!