編寫一個 C 程式來從檔案讀取資料並顯示
問題
如何閱讀存在於檔案中的系列專案並在列或表格中使用 C 程式設計方式顯示資料
解決方案
以寫入模式建立一個檔案,並在檔案中寫一些系列資訊並關閉它,再次開啟並以列的形式在控制檯上顯示資料系列。
開啟檔案的寫入模式
FILE *fp;
fp =fopen ("sample.txt", "w");如果檔案不存在,則將建立一個新檔案。
如果檔案存在,則舊內容會被擦除,當前內容將被儲存。
開啟檔案的讀取模式
FILE *fp
fp =fopen ("sample.txt", "r");如果檔案不存在,則 fopen 函式返回 NULL 值。
如果檔案存在,則資料從檔案中讀取成功。
在控制檯上以表格形式顯示資料的邏輯是 -
while ((ch=getc(fp))!=EOF){
if(ch == ',')
printf("\t\t");
else
printf("%c",ch);
}程式
#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
int main(){
char ch;
FILE *fp;
fp=fopen("std1.txt","w");
printf("enter the text.press cntrl Z:
");
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("std1.txt","r");
printf("text on the file:
");
while ((ch=getc(fp))!=EOF){
if(ch == ',')
printf("\t\t");
else
printf("%c",ch);
}
fclose(fp);
return 0;
}輸出
enter the text.press cntrl Z: Name,Item,Price Bhanu,1,23.4 Priya,2,45.6 ^Z text on the file: Name Item Price Bhanu 1 23.4 Priya 2 45.6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP