C language file read and write operations, write data to files, read and write
It is very time for beginners to learn how to read and write files in linux systems and write data to files.
# Include <stdio. h> int writeInfoToFile (char * strFile) {int age, I; char name [10]; FILE * fp; fp = fopen (strFile, "w "); // open the file in write-only mode if (fp = NULL) {perror ("fopen"); // if the file fails to be opened, print the error message return-1 ;} for (I = 0; I <3; I ++) // write data {printf ("iput age and name: \ n "); scanf ("% d % s", & age, name); fprintf (fp, "% d, % s \ n", age, name) ;}fclose (fp ); // close the file} int main () {char file [20] = "data.txt"; writeInfoToFile (file); // system ("cp file data.csv ");}
How to store data and read data in a C-language one-way linked list
For a while, I wrote a simple example. The example succeeded in vs2005. test.txt is the file name, which is in the current directory.
# Include <stdio. h>
# Include <stdlib. h>
# Define TRUE 1
# Define FALSE 0
Typedef struct Node
{
Int num;
Int score;
Struct Node * next;
} Node, * Linklist;
Void InitLinklist (Linklist * L) // initialize a single-chain table to create a linked list of empty leading nodes.
{
* L = (Node *) malloc (sizeof (Node ));
(* L)-> next = NULL;
}
Void CreateLinklist (Linklist L) // create a single-chain table by means of end insertion
{
Node * r, * s;
R = L;
Int iNum, iScore;
Printf ("Please input the number and score: \ n ");
Scanf ("% d", & iNum );
Scanf ("% d", & iScore );
While (0! = IScore) // when the score is negative, end the input
{
S = (Node *) malloc (sizeof (Node ));
S-> num = iNum;
S-> score = iScore;
R-> next = s;
R = s;
Printf ("Please input the number and score: \ n ");
Scanf ("% d", & iNum );
Scanf ("% d", & iScore );
}
R-> next = NULL; // set the pointer field of the last node to NULL.
}
Int WriteLinklistToFile (const char * strFile, Linklist L)
{
FILE * fpFile;
Node * head = L-> next;
If (NULL = (fpFile = fopen (strFile, "w") // open it in write mode
{
Printf ("Open file failed \ n ");
Return FALSE;
}
While (NULL! = Head)
{
Fprintf (fpFile, "% d \ t % d \ n", head-> num, head-> score );
Head = head-> next;
}
If (NULL! = FpFile)
Fclose (fpFile );
Return TRUE;
};
Int ReadFromFile (const char * strFile)
{
FILE * fpFile;
If (NULL = (fpFile = fopen (strFile, "r") // open it in Read mode
{
Printf ("Open file failed \ n ");
Retur ...... remaining full text>
How to read and write files in C?
You must open the file before reading and writing the file. You can use the fopen or open functions.
As follows:
FILE * fp;
Fp = fopen ("d: \ a.txt", "r +"); // download the.txt file under the d Drive.
Then you can read and write data.