Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to read variables directly from a file with fscanf() function in C

2 Answers

0 votes
#include <stdio.h>
 
// int fscanf(FILE *stream, const char *format, ...) 
 
int main(void)
{
    char  file[20] = "e:\\data.txt";
    FILE *fp;
    int   n;
    char  ch;
    float f;
 
    if ( !(fp = fopen(file, "r")) )
    {
        printf("Error open file: %s", file);
        return 1;
    }
 
    fscanf(fp,"%d %c %f",&n, &ch, &f);
 
    fclose(fp);
     
    printf("n = %d ch = %c f = %.2f\n", n, ch, f);
 
    return 0;
}
 
// file content: 100 a 3.14
 
/*
run:
   
n = 100 ch = a f = 3.14

*/


answered Mar 12, 2015 by avibootz
edited Dec 18, 2015 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
 
// int fscanf(FILE *stream, const char *format, ...) 
 
int main(void)
{
    char s1[13], s2[13], s3[13], s4[13];
    int year;
    FILE * fp;

    fp = fopen ("e:/data.txt", "w+");
    fputs("We love to code 2015", fp);
   
    rewind(fp);
    fscanf(fp, "%s %s %s %s %d", s1, s2, s3, s4, &year);
   
    printf("s1: %s\n", s1 );
    printf("s2: %s\n", s2 );
    printf("s3: %s\n", s3 );
    printf("s4: %s\n", s4 );
    printf("year: %d\n", year );
    
    fclose(fp);
    
    return 0;
}
 
/*
run:
   
s1: We
s2: love
s3: to
s4: code
year: 2015

*/

 



answered Dec 18, 2015 by avibootz

Related questions

1 answer 126 views
1 answer 158 views
1 answer 158 views
2 answers 166 views
1 answer 201 views
...