#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//opening collection.txt using ptr
FILE *ptr;
char data[1000];
ptr = fopen("collection.txt", "r");
printf("Hello world \n");
fscanf(ptr, "%s", data);
printf("%s \n", data);
fclose(ptr);
return 0;
}
collection.txt:
hi my name is
When I run this program I'm getting:
Hello world
P7k
P7k is a memory location I assume.
I've looked at multiple websites and articles and I'm unable to figure out what I can do to print the text in collection.txt
"%s" only scans until it finds a white character. My suggestion would be to scan the file letter by letter ("%c") until you find end of file. Something like:
while(!feof(ptr)) {
fscanf(ptr, %c, data + counter); counter++;
}
Problems include
Not testing for fopen()
success
FILE *ptr;
// add
if (ptr == NULL) {
fprintf(stderr, "Fail to open\n");
return -1;
}
Not testing for fscanf()
success
// fscanf(ptr, "%s", data);
if (fscanf(ptr, "%s", data) != 1) {
fprintf(stderr, "Fail to read\n");
return -1;
}
Not limiting input
char data[1000];
// fscanf(ptr, "%s", data);
fscanf(ptr, "%999s", data);
Not reporting all data
"%s"
does not save white space, so white-space from the file is not printed.
Use fgets()
to read a line of input. To read all, use a loop.
while (fgets(data, sizeof data, ptr)) {
printf("%s", ptr);
}
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.