在資料結構中,我們不再只使用 IDE 作為編譯、測試的工具,而是得直接使用 PowerShell 作為編譯、輸入測資的工具。這篇文章將會簡單講述怎麼用 PowerShell、VS code 來使用讀檔,寫檔
檔案處理中最為基礎的東西,假設滑鼠游標稱為【read_dart】,檔案開啟時,read_dart 會置於檔案的開頭位置,接著循序向下讀取資料,直到檔案的結尾。
讀取資料是檔案結構中最為重要的一部份,可以說不會資料的輸入與輸出就是不會檔案處理。
#include <stdio.h>
int main(){
// 創建指標指向要開啟的檔案,"r"讀取資料,"w"格式化開啟檔案並輸出資料
FILE *input, *output;
input = fopen("input.txt", "r");
output = fopen("output.txt", "w");
// 字元陣列與字元
char str[10000];
char ch;
// 檔案開啟的除錯
if(input == NULL){
printf("input.txt open read mode failed.\\n");
}
if(output == NULL){
printf("output.txt open write mode failed.\\n");
}
// 輸入
fscanf(input, "%s", str); // 與 scanf 相同,遇到空格自動停下
fgets(str, 10000, input); // 與 getline(cin, input) 相同,讀入一整行包含空白
ch = fgetc(input); // 與 getchar 相同,單取一個字元變數
// 輸出
fprintf(output, "%s %c\\n", str, ch); // 與 printf 一樣,可以排版
fputc(ch, output) // 單純輸出一個字元
// 將讀取的位置重置到檔案開頭位置
rewind(input);
// 關檔
fclose(input);
fclose(output);
}
while(fscanf(input, "%s", str) != EOF){}
while(fgets(str, 10000, input) != NULL){}
while(fgetc(input)){}
.csv 檔案以 ,
作為數字分隔值,輸出時請記得在數字後加上一個 ,
fprintf(output_file_name, "%d,", number_for_output);
最近做題目時,常常會有數字的測資進來,但是苦於字元陣列與數字的轉換,這邊整理幾個常見的解法。
目前來說數字轉字串以 sprintf 最為穩定,因此建議取代掉 itoa ,只需要記得 atoi、sprintf。
// 標頭檔,必須引用
#include <stdlib.h>
// 目標字串
char str[3] = ['1', '2', '3'];
// 字串轉數字:數字資料型態 = atoi(目標字元陣列)
int n = atoi(str);
// 數字轉字串:itoa(數字, 目標字元陣列, 進位制底數)
itoa(n, str, 10);
// itoa 也可以寫成以下
sprintf(str, "%d", number); // itoa(number, str, 10);