guys i want to read the text from my file and assign every character to a single element of the array
char A[1000];
FILE * fpointer;
fpointer=fopen("text.txt","r");
i=0;
while(!feof(fpointer))
{
fscanf(fpointer,"%c",&A[i]);
i=i+1;
}
fclose(fpointer);
for (i=0;i<100;i++)
{
printf("%c",A[i]);
}
return 0;
but the problem is that the output is some weird symbols instead of the file's text which is "This is just a test".Why is that happening ?
Possible reasons include:
fopen
failed to open the specified file. Fix by checking the return value of fopen
.i
.Corrected code snippet:
int i = 0, j = 0;
char A[1000];
FILE* fpointer;
fpointer = fopen("text.txt", "r");
if(!fpointer)
{
fputs("fopen failed! Exiting...\n", stderr);
exit(-1); /* Requires `stdlib.h` */
}
while(fscanf(fpointer, "%c", &A[i]) != EOF)
{
i = i + 1;
}
fclose(fpointer);
for (j = 0; j < i; j++){
printf("A[%d] = '%c'\n", j, A[j]);
}