C語言檔案讀寫操作,寫入資料到檔案,讀寫
很早寫的在linux系統下的檔案讀寫操作,寫入資料到檔案,很時候初學者學習
#include <stdio.h>int writeInfoToFile(char *strFile){int age, i;char name[10];FILE *fp;fp = fopen(strFile, "w");// 唯寫的方式開啟檔案if(fp == NULL){perror("fopen");// 檔案開啟失敗,列印錯誤資訊return -1;}for(i=0; i<3; i++)// 寫入資料{printf("iput age and name:\n");scanf("%d %s", &age, name);fprintf(fp, "%d,%s\n", age, name);}fclose(fp);// 關閉檔案}int main(){char file[20] = "data.txt";writeInfoToFile(file);//system("cp file data.csv");}
C語言單向鏈表,怎往檔案裡存入資料與讀取資料
花了我半個小時,給了寫了一個簡單的例子,以下是在vs2005下調試成功,test.txt為檔案名稱,在目前的目錄下。
#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) //初始化單鏈表,建立空的帶頭結點的鏈表
{
*L = (Node*)malloc(sizeof(Node));
(*L)->next = NULL;
}
void CreateLinklist(Linklist L) //尾插法建立單鏈表
{
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) //當成績為負時,結束輸入
{
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; //將最後一個節點的指標域置為空白
}
int WriteLinklistToFile(const char* strFile, Linklist L)
{
FILE *fpFile;
Node *head = L->next;
if(NULL == (fpFile = fopen(strFile,"w"))) //以寫的方式開啟
{
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"))) //以讀的方式開啟
{
printf("Open file failed\n");
retur......餘下全文>>
C語言中對檔案進行讀寫操作必須先將檔案怎辦
在對檔案進行讀寫之前必須 先開啟檔案,可使用fopen或者open 函數。
如下:
FILE *fp;
fp=fopen("d:\\a.txt","r+");//打下D盤下的a.txt檔案
然後你就可以進行讀寫了。