C語言檔案讀寫操作,寫入資料到檔案,讀寫

來源:互聯網
上載者:User

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檔案
然後你就可以進行讀寫了。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.