Home > Net >  fscanf printing replacement character
fscanf printing replacement character

Time:11-21

#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

CodePudding user response:

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, "           
  • Related