2017年4月10日 星期一

C&sql

使用C寫入資料庫

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char *argv[]) {
int account;
char name[30];
double balance;
FILE *cfptr;
if((cfptr=fopen("clients2.dat","w"))==NULL){
printf("file could not be opened\n");

}
else{
printf("enter the account ,name,and balance.\n");
printf("enter EOF to end inpute.\n");
printf("?");
scanf("%d%s%.2f",&account,name,&balance);
while(!feof(stdin)){
fprintf(cfptr,"%d %s %.2f\n",account,name,balance);
printf("?");
scanf("%d%s%lf",&account,name,&balance);

}
fclose(cfptr);
}
return 0;
}


PS1:寫入同檔案夾中的資料庫,名字取決於此處clients2:if((cfptr=fopen("clients2.dat","w"))==NULL){
PS2:fopen(檔案名稱, 模式) 以指定模式開啟檔案 其中"W"代表寫入
*************************
使用C讀入資料庫
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
int account;
char name[30];
double balance;
FILE *cfptr;
if((cfptr=fopen("clients.dat","r"))==NULL){
printf("could not open\n");

}
else {
printf("%-10s%-13s%s\n","account","name","balance");
fscanf(cfptr,"%d%s%lf",&account,name,&balance);
while(!feof(cfptr)){
printf("%-10d%-13s%7.2f\n",account,name,balance);
fscanf(cfptr,"%d%s%lf",&account,name,&balance);
}
fclose(cfptr);
}
return 0;
}

沒有留言:

張貼留言