Use fscanf to read text files

Source: Internet
Author: User

Fscanf is a c api for reading text files. It features formatting and reading of file content.

1 FILE* pf = fopen("c:\\hello.txt", "r");
2  if (NULL==pf)
3 return;
4
5  char cstr[256];
6 fscanf(pf, "%s", cstr);
7 fclose(pf);

Fscanf uses spaces, tabs, and carriage returns to separate different words, making it easier to use.

Fscanf is encapsulated to search for target characters, read strings, integers, and double-precision floating point numbers.

 1 #pragma once 
2 #pragma warning (disable:4996)
3
4 inline bool HitFlag(FILE* pf, const char* flag)
5 {
6 char chs[256];
7 while (!feof(pf))
8 {
9 fscanf(pf, "%s", chs);
10 if (0==strcmp(flag, chs))
11 return true;
12 }
13
14 return false;
15 }
16
17 inline std::string ReadStrVal(FILE* pf)
18 {
19 char chs[256];
20 fscanf(pf, "%s", chs);
21 return std::string(chs);
22 }
23
24 inline int ReadIntVal(FILE* pf)
25 {
26 int iVal;
27 fscanf(pf, "%d", &iVal);
28 return iVal;
29 }
30
31 inline double ReadDblVal(FILE* pf)
32 {
33 double fVal;
34 fscanf(pf, "%lf", &fVal);
35 return fVal;
36 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.