C 语言

精选 C 语言 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#入门指南

#hello.c 示例 示例

#include <stdio.h>

int main(void) {
  printf("Hello World!\n");

  return 0;
}

使用 gcc 编译 hello.c 文件

$ gcc -Wall -g hello.c -o hello

运行编译后的二进制文件 hello

$ ./hello

输出 => Hello World!

#变量声明 (Variables)

int myNum = 15;

int myNum2; // do not assign, then assign
myNum2 = 15;

int myNum3 = 15; // myNum3 is 15
myNum3 = 10;     // myNum3 is now 10

float myFloat = 5.99; // floating point number
char myLetter = 'D';  // character

int x = 5;
int y = 6;
int sum = x + y; // add variables to sum

// declare multiple variables
int a = 5, b = 6, c = 50;

#常量 (Constants)

const int minutesPerHour = 60;
const float PI = 3.14;

Best Practices

const int BIRTHYEAR = 1980;

#代码注释 (Comments)

// this is a comment
printf("Hello World!\n"); // Can comment anywhere in file

/*Multi-line comment, print Hello World!
to the screen, it's awesome */

#输出文本 (Print text)

printf("I am learning C.\n");
int testInteger = 5;
printf("Number = %d\n", testInteger);

float f = 5.99; // floating point number
printf("Value = %f\n", f);

short a = 0b1010110; // binary number
int b = 02713; // octal number
long c = 0X1DAB83; // hexadecimal number

// output in octal form
printf("a=%ho, b=%o, c=%lo\n", a, b, c);
// output => a=126, b=2713, c=7325603

// Output in decimal form
printf("a=%hd, b=%d, c=%ld\n", a, b, c);
// output => a=86, b=1483, c=1944451

// output in hexadecimal form (letter lowercase)
printf("a=%hx, b=%x, c=%lx\n", a, b, c);
// output => a=56, b=5cb, c=1dab83

// Output in hexadecimal (capital letters)
printf("a=%hX, b=%X, c=%lX\n", a, b, c);
// output => a=56, b=5CB, c=1DAB83

#控制空格数量

int a1 = 20, a2 = 345, a3 = 700;
int b1 = 56720, b2 = 9999, b3 = 20098;
int c1 = 233, c2 = 205, c3 = 1;
int d1 = 34, d2 = 0, d3 = 23;

printf("%-9d %-9d %-9d\n", a1, a2, a3);
printf("%-9d %-9d %-9d\n", b1, b2, b3);
printf("%-9d %-9d %-9d\n", c1, c2, c3);
printf("%-9d %-9d %-9d\n", d1, d2, d3);

output result

20        345       700
56720     9999      20098
233       205       1
34        0         23

In %-9d, d means to output in 10 base, 9 means to occupy at least 9 characters width, and the width is not enough to fill with spaces, - means left alignment

#字符串 (Strings)

char greetings[] = "Hello World!";
printf("%s", greetings);

Access string

char greetings[] = "Hello World!";
printf("%c", greetings[0]);

Modify string

char greetings[] = "Hello World!";
greetings[0] = 'J';

printf("%s", greetings);
// prints "Jello World!"

Another way to create a string

char greetings[] = {'H','e','l','l','\0'};

printf("%s", greetings);
// print "Hell!"

Creating String using character pointer (String Literals)

char *greetings = "Hello";
printf("%s", greetings);
// print "Hello!"

NOTE: String literals might be stored in read-only section of memory. Modifying a string literal invokes undefined behavior. You can't modify it!

C does not have a String type, use char type and create an array of characters

#Condition

int time = 20;
if (time < 18) {
  printf("Goodbye!\n");
} else {
  printf("Good evening!\n");
}
// Output -> "Good evening!"
int time = 22;
if (time < 10) {
  printf("Good morning!\n");
} else if (time < 20) {
  printf("Goodbye!\n");
} else {
  printf("Good evening!\n");
}
// Output -> "Good evening!"

#Ternary operator

int age = 20;
(age > 19) ? printf("Adult\n") : printf("Teenager\n");

#Switch

int day = 4;

switch (day) {
  case 3: printf("Wednesday\n"); break;
  case 4: printf("Thursday\n"); break;
  default:
    printf("Weekend!\n");
}
// output -> "Thursday" (day 4)

#While Loop

int i = 0;

while (i < 5) {
  printf("%d\n", i);
  i++;
}

NOTE: Don't forget to increment the variable used in the condition, otherwise the loop will never end and become an "infinite loop"!

#Do/While Loop

int i = 0;

do {
  printf("%d\n", i);
  i++;
} while (i < 5);

#For Loop

for (int i = 0; i < 5; i++) {
  printf("%d\n", i);
}

#Break out of the loop Break/Continue

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  printf("%d\n", i);
}

Break out of the loop when i is equal to 4

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  printf("%d\n", i);
}

Example to skip the value of 4

#While Break Example

int i = 0;

while (i < 10) {
  if (i == 4) {
    break;
  }
  printf("%d\n", i);

  i++;
}

#While continue example

int i = 0;

while (i < 10) {
  i++;

  if (i == 4) {
    continue;
  }
  printf("%d\n", i);
}

#Arrays

int myNumbers[] = {25, 50, 75, 100};

printf("%d", myNumbers[0]);
// output 25

Change array elements

int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf("%d", myNumbers[0]);

Loop through the array

int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {
  printf("%d\n", myNumbers[i]);
}

Set array size

// Declare an array of four integers:
int myNumbers[4];

// add element
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

#Enumeration Enum

enum week { Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun };

Define enum variable

enum week a, b, c;
enum week { Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun } a, b, c;

With an enumeration variable, you can assign the value in the list to it

enum week { Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun };
enum week a = Mon, b = Wed, c = Sat;
// or
enum week{ Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun } a = Mon, b = Wed, c = Sat;

#Enumerate sample applications

enum week {Mon = 1, Tues, Wed, Thurs} day;

scanf("%d", &day);

switch(day) {
  case Mon: puts("Monday"); break;
  case Tues: puts("Tuesday"); break;
  case Wed: puts("Wednesday"); break;
  case Thurs: puts("Thursday"); break;
  default: puts("Error!");
}

#User input

// Create an integer variable to store the number we got from the user
int myNum;

// Ask the user to enter a number
printf("Enter a number: ");

// Get and save the number entered by the user
scanf("%d", &myNum);

// Output the number entered by the user
printf("The number you entered: %d\n", myNum);

#User input string

// create a string
char firstName[30];
// Ask the user to enter some text
printf("Enter your name: ");
// get and save the text
scanf("%s", &firstName);
// output text
printf("Hello %s.\n", firstName);

#memory address

When a variable is created, it is assigned a memory address

int myAge = 43;

printf("%p", &myAge);
// Output: 0x7ffe5367e044

To access it, use the reference operator (&)

#create pointer

int myAge = 43; // an int variable
printf("%d\n", myAge); // output the value of myAge(43)

// Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", &myAge);

#pointer variable

int myAge = 43; // an int variable
int*ptr = &myAge; // pointer variable named ptr, used to store the address of myAge

printf("%d\n", myAge); // print the value of myAge (43)

printf("%p\n", &myAge); // output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", ptr); // use the pointer (0x7ffe5367e044) to output the memory address of myAge

#Dereference

int myAge = 43; // variable declaration
int*ptr = &myAge; // pointer declaration

// Reference: output myAge with a pointer
// memory address (0x7ffe5367e044)
printf("%p\n", ptr);
// dereference: output the value of myAge with a pointer (43)
printf("%d\n", *ptr);

#Operators

#Arithmetic Operators

int myNum = 100 + 50;
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Operator Name Example
+ Add x + y
- Subtract x - y
* Multiply x * y
/ Divide x / y
% Modulo x % y
++ Increment ++x
-- Decrement --x

#Assignment operator

Example As
x = 5 x = 5
x += 3 x = x + 3
x -= 3 x = x - 3
x *= 3 x = x * 3
x /= 3 x = x / 3
x %= 3 x = x % 3
x &= 3 x = x & 3
x |= 3 x = x | 3
x ^= 3 x = x ^ 3
x >>= 3 x = x >> 3
x <<= 3 x = x << 3

#Comparison Operators

int x = 5;
int y = 3;

printf("%d", x > y);
// returns 1 (true) because 5 is greater than 3

Symbol Name Example
== equals x == y
!= not equal to x != y
> greater than x > y
< less than x < y
>= greater than or equal to x >= y
<= less than or equal to x <= y

Comparison operators are used to compare two values

#Logical Operators

Symbol Name Description Example
&& and logical returns true if both statements are true x < 5 && x < 10
|| or logical returns true if one of the statements is true x < 5 || x < 4
! not logical Invert result, return false if true !(x < 5 && x < 10)
运算符 名称 示例
+ 加法 x + y
- 减法 x - y
* 乘法 x * y
/ 除法 x / y
% 取模 x % y
++ 递增 ++x
-- 递减 --x

#赋值运算符 (Assignment operator)

示例 等同于
x = 5 x = 5
x += 3 x = x + 3
x -= 3 x = x - 3
x *= 3 x = x * 3
x /= 3 x = x / 3
x %= 3 x = x % 3
x &= 3 x = x & 3
x |= 3 x = x | 3
x ^= 3 x = x ^ 3
x >>= 3 x = x >> 3
x <<= 3 x = x << 3

#比较运算符 (Comparison Operators)

int x = 5;
int y = 3;

printf("%d", x > y);
// returns 1 (true) because 5 is greater than 3

符号 名称 示例
== 等于 x == y
!= 不等于 x != y
> 大于 x > y
< 小于 x < y
>= 大于或等于 x >= y
<= 小于或等于 x <= y

比较运算符用于比较两个值

#逻辑运算符 (Logical Operators)

符号 名称 描述 示例
&& 逻辑与 如果两个语句都为真则返回真 x < 5 && x < 10
|| 逻辑或 如果其中一个语句为真则返回真 x < 5 || x < 4
! 逻辑非 反转结果,如果为真则返回假 !(x < 5 && x < 10)

#运算符示例 (Operator Examples)

unsigned int a = 60; /*60 = 0011 1100 */
unsigned int b = 13; /*13 = 0000 1101 */
int c = 0;

c = a & b; /*12 = 0000 1100 */
printf("Line 1 -the value of c is %d\n", c);

c = a | b; /*61 = 0011 1101 */
printf("Line 2 -the value of c is %d\n", c);
c = a ^ b; /*49 = 0011 0001 */
printf("Line 3 -the value of c is %d\n", c);
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 -The value of c is %d\n", c);
c = a << 2; /*240 = 1111 0000 */
printf("Line 5 -the value of c is %d\n", c);
c = a >> 2; /*15 = 0000 1111 */
printf("Line 6 -The value of c is %d\n", c);

#位运算符 (Bitwise operators)

运算符 描述 实例
& 按位与运算,按二进制位进行"与"运算 (A & B) 将得到 12 即 0000 1100
| 按位或运算,按二进制位进行"或"运算 (A | B) 将得到 61 即 0011 1101
^ 异或运算,按二进制位进行"异或"运算 (A ^ B) 将得到 49 即 0011 0001
~ 取反运算,按二进制位进行"取反"运算 (~A) 将得到 -61 即 1100 0011
<< 二进制左移运算符 A << 2 将得到 240 即 1111 0000
>> 二进制右移运算符 A >> 2 将得到 15 即 0000 1111

#数据类型

#基本数据类型 (Basic data types)

数据类型 大小 范围 描述
char 1 字节 −128 ~ 127 单个字符/字母数字/ASCII
signed char 1 字节 −128 ~ 127
unsigned char 1 字节 0 ~ 255
int 24 字节 −32,768 ~ 32,767 存储整数
signed int 2 字节 −32,768 ~ 32,767
unsigned int 2 字节 0 ~ 65,535
short int 2 字节 −32,768 ~ 32,767
signed short int 2 字节 −32,768 ~ 32,767
unsigned short int 2 字节 0 ~ 65,535
long int 4 字节 -2,147,483,648 ~ 2,147,483,647
signed long int 4 字节 -2,147,483,648 ~ 2,147,483,647
unsigned long int 4 字节 0 ~ 4,294,967,295
float 4 字节 3.4E-38 ~ 3.4E+38
double 8 字节 1.7E-308 ~ 1.7E+308
long double 10 字节 3.4E-4932 ~ 1.1E+4932

#数据类型

// create variables
int myNum = 5; // integer
float myFloatNum = 5.99; // floating point number
char myLetter = 'D'; // string
// High precision floating point data or numbers
double myDouble = 3.2325467;
// print output variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
printf("%lf\n", myDouble);

数据类型 描述
char 字符类型
short 短整型
int 整数类型
long 长整型
float 单精度浮点类型
double 双精度浮点类型
void 无类型

#基本格式说明符 (Basic format specifiers)

格式说明符 数据类型
%d%i int 整数
%f float 单精度十进制类型
%lf double 高精度浮点数据或数字
%c char 字符
%s 用于 strings 字符串

#分隔基数格式说明符 (Separate base format specifiers)

格式 Short Int Long
八进制 %ho %o %lo
十进制 %hd %d %ld
十六进制 %hx / %hX %x / %X %lx / %lX

#数据格式示例 (Data format example)

int myNum = 5;
float myFloatNum = 5.99; // floating point number
char myLetter = 'D';     // string
// print output variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

#C 预处理器

#预处理器指令 (Preprocessor Directives)

指令 描述
#define 定义宏
#include 包含一个源代码文件
#undef 取消定义宏
#ifdef 如果宏已定义则返回真
#ifndef 如果宏未定义则返回真
#if 如果给定条件为真则编译下面代码
#else #if 的替代方案
#elif 如果 #if 条件为假,当前条件为真
#endif 结束一个 #if...#else 条件编译块
#error 当遇到标准错误时打印错误消息
#pragma 使用标准化方法向编译器发出特殊命令
// replace all MAX_ARRAY_LENGTH with 20
#define MAX_ARRAY_LENGTH 20
// Get stdio.h from the system library
#include <stdio.h>
// Get myheader.h in the local directory
#include "myheader.h"
#undef FILE_SIZE
#define FILE_SIZE 42 // undefine and define to 42

#预定义宏 (Predefined macros)

描述
__DATE__ 当前日期,一个以 "MMM DD YYYY" 格式的字符常量
__TIME__ 当前时间,一个以 "HH:MM:SS" 格式的字符常量
__FILE__ 这会包含当前文件名,一个字符串常量
__LINE__ 这会包含当前行号,一个十进制常量
__STDC__ 当编译器以 ANSI 标准编译时,则定义为 1

ANSI C 定义了许多宏,你可以使用这些宏,但不能直接修改这些预定义宏

预定义宏示例

#include <stdio.h>

int main(void) {
  printf("File: %s\n", __FILE__);
  printf("Date: %s\n", __DATE__);
  printf("Time: %s\n", __TIME__);
  printf("Line: %d\n", __LINE__);
  printf("ANSI: %d\n", __STDC__);
}

#宏延续运算符 (\) (Macro continuation operator (\))

一个宏通常写在一个单行上

#define message_for(a, b) \
    printf(#a " and " #b ": We love you!\n")

如果宏太长,无法写在一行,则使用宏延续运算符 \

#字符串常量化运算符 (#) (String Constantization Operator (#))

#include <stdio.h>

#define message_for(a, b) \
  printf(#a " and " #b ": We love you!\n")

int main(void) {
  message_for(Carole, Debra);

  return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

Carole and Debra: We love you!

当需要把一个宏的参数转换为字符串常量时,则使用字符串常量化运算符 #

#标记粘贴运算符 (##) (tag paste operator (##))

#include <stdio.h>

#define tokenpaster(n) printf ("Token " #n " = %d\n", token##n)

int main(void) {
  int token34 = 40;
  tokenpaster(34);

  return 0;
}

#defined() 运算符 (defined() operator)

#include <stdio.h>

#if !defined (MESSAGE)
   #define MESSAGE "You wish!"
#endif

int main(void) {
  printf("Here is the message: %s\n", MESSAGE);

  return 0;
}

#参数化的宏 (Parameterized macros)

int square(int x) {
  return x * x;
}

宏重写上面的代码,如下:

#define square(x) ( (x) * (x) )

在宏名称和左圆括号之间不允许有空格

#include <stdio.h>
#define MAX(x,y) ( (x) > (y) ? (x) : (y) )

int main(void) {
  printf("Max between 20 and 10 is %d\n", MAX(10, 20));

  return 0;
}

#C 函数

#函数声明和定义 (Function declaration and definition)

int main(void) {
  printf("Hello World!\n");

  return 0;
}

函数由两部分组成

void myFunction() { // declaration declaration
  // function body (code to be executed) (definition)
}

  • Declaration 声明函数名称、返回类型和参数 (如果有)
  • Definition 函数体 (要执行的代码)

// function declaration
void myFunction();
// main method
int main() {
  myFunction(); // --> call the function

  return 0;
}

void myFunction() {// Function definition
  printf("Good evening!\n"); // 输出:晚上好!
}

#调用函数 (Call function)

// create function
void myFunction() {
  printf("Good evening!\n"); // 输出:晚上好!
}

int main() {
  myFunction(); // call the function
  myFunction(); // can be called multiple times

  return 0;
}
// 输出结果 -> "Good evening!"
// 输出结果 -> "Good evening!"

#函数参数 (Function parameters)

void myFunction(char name[]) {
  printf("Hello %s\n", name);
}

int main() {
  myFunction("Liam");
  myFunction("Jenny");

  return 0;
}
// Hello Liam
// Hello Jenny

#多个参数 (Multiple parameters)

void myFunction(char name[], int age) {
  printf("Hi %s, you are %d years old.\n",name,age);
}
int main() {
  myFunction("Liam", 3);
  myFunction("Jenny", 14);

  return 0;
}
// Hi Liam you are 3 years old.
// Hi Jenny you are 14 years old.

#返回值 (Return value)

int myFunction(int x) {
  return 5 + x;
}

int main() {
  printf("Result: %d\n", myFunction(3));
  return 0;
}
// output 8 (5 + 3)

两个参数

int myFunction(int x, int y) {
  return x + y;
}

int main() {
  printf("Result: %d\n", myFunction(5, 3));
  // store the result in a variable
  int result = myFunction(5, 3);
  printf("Result = %d\n", result);

  return 0;
}
// result: 8 (5 + 3)
// result = 8 (5 + 3)

#递归示例 (递归处理 example)

int sum(int k);

int main() {
  int result = sum(10);
  printf("%d\n", result);

  return 0;
}

int sum(int k) {
  if (k > 0) {
    return k + sum(k -1);
  } else {
    return 0;
  }
}

#数学函数 (Mathematical functions)

#include <math.h>

void main(void) {
  printf("%f\n", sqrt(16)); // square root
  printf("%f\n", ceil(1.4)); // round up (round)
  printf("%f\n", floor(1.4)); // round down (round)
  printf("%f\n", pow(4, 3)); // x(4) to the power of y(3)
}

  • abs(x) 绝对值
  • acos(x) 反余弦值
  • asin(x) 反正弦
  • atan(x) 反正切
  • cbrt(x) 立方根
  • cos(x) 余弦
  • exp(x) Ex 的值
  • sin(x) x 的正弦
  • tan(x) 角的正切

#C 结构

#创建结构 (Create structure)

struct MyStructure { // structure declaration
  int myNum; // member (int variable)
  char myLetter; // member (char variable)
}; // end the structure with a semicolon

创建一个名为 s1 的结构体变量

struct myStructure {
  int myNum;
  char myLetter;
};

int main() {
  struct myStructure s1;

  return 0;
}

#结构中的字符串 (Strings in the structure)

struct myStructure {
  int myNum;
  char myLetter;
  char myString[30]; // String
};

int main() {
  struct myStructure s1;
  strcpy(s1. myString, "Some text");
  // print value
  printf("My string: %s\n", s1.myString);

  return 0;
}

使用 strcpy 函数为字符串赋值

#访问结构成员 (Accessing structure members)

// create a structure called myStructure
struct myStructure {
  int myNum;
  char myLetter;
};

int main() {
  // Create a structure variable called myStructure called s1
  struct myStructure s1;
  // Assign values ​​to the members of s1
  s1.myNum = 13;
  s1.myLetter = 'B';

  // Create a structure variable of myStructure called s2
  // and assign it a value
  struct myStructure s2 = {13, 'B'};
  // print value
  printf("My number: %d\n", s1.myNum);
  printf("My letter: %c\n", s1.myLetter);

  return 0;
}

创建不同的结构变量

struct myStructure s1;
struct myStructure s2;
// Assign values ​​to different structure variables
s1.myNum = 13;
s1.myLetter = 'B';

s2.myNum = 20;
s2.myLetter = 'C';

#复制结构 (Copy structure)

struct myStructure s1 = {
  13, 'B', "Some text"
};

struct myStructure s2;
s2 = s1;

在示例中,s1 的值被复制到 s2

#修改值 (Modify value)

// Create a struct variable and assign it a value
struct myStructure s1 = {
  13, 'B'
};
// modify the value
s1.myNum = 30;
s1.myLetter = 'C';
// print value
printf("%d %c",
    s1.myNum,
    s1.myLetter);

#文件处理

#文件处理函数 (File processing function)

函数 描述
fopen() 打开新文件或现有文件
fprintf() 文件写入数据
fscanf() 从文件读取数据
fputc() 文件写入一个字符
fgetc() 从文件读取一个字符
fclose() 关闭文件
fseek() 将文件指针设置为给定位置
fputw() 向文件写入一个整数
fgetw() 从文件读取一个整数
ftell() 返回当前位置
rewind() 将文件指针设置到文件的开头

C 库中有许多函数用于打开/读取/写入/搜索关闭文件

#打开模式参数 (Open mode parameter)

模式 描述
r 读取模式打开文本文件,允许读取文件
w 写入模式打开文本文件,允许写入文件
a 追加模式打开文本文件
如果文件不存在,将创建一个新文件
r+ 读写模式打开文本文件,允许读取和写入文件
w+ 读写模式打开文本文件,允许读取和写入文件
a+ 读写模式打开文本文件,允许读取和写入文件
rb 读取模式打开二进制文件
wb 写入模式打开二进制文件
ab 追加模式打开二进制文件
rb+ 读写模式打开二进制文件
wb+ 读写模式打开二进制文件
ab+ 读写模式打开二进制文件

#打开文件:fopen() (Open the file: fopen())

#include <stdio.h>

void main() {
  FILE *fp;
  char ch;

  fp = fopen("file_handle.c", "r");

  while (1) {
    ch = fgetc(fp);
    if (ch == EOF)
      break;
    printf("%c", ch);
  }
  fclose(fp);
}

在对文件执行所有操作后,必须使用 fclose() 关闭文件

#写入文件:fprintf() (Write to file: fprintf())

#include <stdio.h>

void main() {
  FILE *fp;
  fp = fopen("file.txt", "w"); // open the file

  // write data to file
  fprintf(fp, "Hello file for fprintf..\n");
  fclose(fp); // close the file
}

#读取文件:fscanf() (Read the file: fscanf())

#include <stdio.h>

void main() {
  FILE *fp;

  char buff[255]; // Create a char array to store file data
  fp = fopen("file.txt", "r");

  while(fscanf(fp, "%s", buff) != EOF) {
    printf("%s ", buff);
  }
  fclose(fp);
}

#写入文件:fputc() (Write to file: fputc())

#include <stdio.h>

void main() {
  FILE *fp;
  fp = fopen("file1.txt", "w"); // open the file
  fputc('a',fp); // write a single character to the file
  fclose(fp); // close the file
}

#读取文件:fgetc() (Read the file: fgetc())

#include <stdio.h>
#include <conio.h>

void main() {
  FILE *fp;
  char c;

  clrscr();

  fp = fopen("myfile.txt", "r");

  while( (c = fgetc(fp) ) != EOF) {
    printf("%c", c);
  }
  fclose(fp);

  getch();
}

#写入文件:fputs() (Write to file: fputs())

#include<stdio.h>
#include<conio.h>

void main() {
  FILE *fp;

  clrscr();

  fp = fopen("myfile2.txt","w");
  fputs("hello c programming",fp);
  fclose(fp);

  getch();
}

#读取文件:fgets() (Read files: fgets())

#include<stdio.h>
#include<conio.h>

void main() {
  FILE *fp;
  char text[300];

  clrscr();

  fp = fopen("myfile2.txt", "r");
  printf("%s", fgets(text, 200, fp));
  fclose(fp);

  getch();
}

#fseek() 函数

#include <stdio.h>

void main(void) {
  FILE *fp;

  fp = fopen("myfile.txt","w+");
  fputs("This is Book", fp);

  // Set file pointer to the given position
  fseek(fp, 7, SEEK_SET);

  fputs("Kenny Wong", fp);
  fclose(fp);
}

将文件指针设置为给定位置

#rewind() 函数

#include <stdio.h>
#include <conio.h>

void main() {
  FILE *fp;
  char c;

  clrscr();

  fp = fopen("file.txt", "r");

  while( (c = fgetc(fp) ) != EOF) {
    printf("%c", c);
  }

  rewind(fp); // move the file pointer to the beginning of the file

  while( (c = fgetc(fp) ) != EOF) {
    printf("%c", c);
  }
  fclose(fp);

  getch();
}
// output
// Hello World! Hello World!

#ftell() 函数

#include <stdio.h>
#include <conio.h>

void main () {
   FILE *fp;
   int length;

   clrscr();

   fp = fopen("file.txt", "r");

   fseek(fp, 0, SEEK_END);
   length = ftell(fp); // return current position
   fclose(fp);

   printf("File size: %d bytes", length);

   getch();
}
// output
// file size: 18 bytes