# Linux Kernel開發學習日誌2020.1.31
###### tags: `linux2020` `C`
## Tree map
```
course week1
└── linux-kernel_rcf
├── c_structure
└── file_IO
└── fwrite() --> in Example3
└── fread() --> in Example4
```
## TODO:
* c file_IO-example3-reading and writing to a binary file.
To write into a
### Example3: Write to a binary file using ```fwrite()```
```c=1
/*
* Created by unknowntpo at 2020.1.30 (Fri)
* @title : Write to a binary file using fwrite()
* @ref : https://www.programiz.com/c-programming/c-file-input-output
* @abstract : write to a binary file using fwrite()
*
*/
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr; // pointer to the file location
if ((fptr = fopen("program.bin", "wb")) == NULL){
printf("Error when opening file");
// pointer exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n){
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
/* fwrite(addressData, sizeData, numbersData, pointerToFile) */
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
```
### Example4: Read from a binary file using ```fread()```
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms,
* you read one ```threeNum``` record of ```threeNum```
* from the file pointed by ```*fptr```
* into the structure num.
You'll get the same records you inserted in Example 3.
```c=1
/*
* Created by unknowntpo at 2020.1.30 (Fri)
* @title : Read to a binary file using fread()
* @ref : https://www.programiz.com/c-programming/c-file-input-output
* @abstract : Read to a binary file using fread()
*
*/
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
}; // struct variable ??
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("program.bin", "rb")) == NULL){
printf("Error! opening file.");
// program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n){ // ++n vs n++ ?
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
// try without fclose --> nothing special happened.
fclose(fptr);
return 0;
}
```
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
## ```strcpy()```: String Copy
The ```strcpy()``` function is defined in the ```string.h``` header file.
* Syntax:
```char* strcpy(char* dest, const char* src);```
* dest: Pointer to the destination array where the content is to be copied.
* src : string which will be copied.
**eg.**
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10]= "awesome";
char str2[10];
char str3[10];
strcpy(str2, str1);
strcpy(str3, "well");
puts(str2);
puts(str3);
return 0;
}
```
Output:
```shell
awesome
well
```
## C Structures
ref : https://www.tutorialspoint.com/cprogramming/c_structures.htm
* struct variable ??