[英]How to read a 4 column text file into two char arrays in C?
C - 如何將4列文件讀入兩個字符串數組
我試圖讀取一個長度未知的文件,其格式如下:
2082018 1200 79 Meeting
3082018 1300 60 Lunch
4082018 1400 30 Dinner
5082018 0600 90 Work
我試圖獲取數組KEY_arr中的第一列和VAL_arr中的其余列,以便:
KEY_Arr[0]
=“2082018”和VAL_arr[0]
=“1200 79會議”
我嘗試了兩種方法,都不成功。 在第一種方法中,我嘗試使用2D數組中的getc讀取文件:
int main(int argc, char** argv) {
FILE *inp_cal;
int word_count = 0;
char c;
char arr[50][50];
int char_count = 0;
int space_cnt = 0;
char line[100];
int line_count = 0;
inp_cal = fopen("calendar_out.txt", "r");
if (inp_cal) {
printf("Processing file...\n");
while ((c = fgetc(inp_cal)) != EOF) {
if ((c == ' ' || c == '\n') && space_cnt == 0) {
arr[word_count][char_count] = '\0'; //Terminate the string
char_count = 0; //Reset the counter.
word_count++;
space_cnt = 1;
} else {
if ((c == ' ' || c == '\n') && space_cnt == 1) {
word_count++;
char_count = 0;
}
arr[word_count][char_count] = c;
printf("%c", arr[word_count][char_count]);
if (char_count < 50) {
char_count++;
} else {
char_count = 0;
}
}
}
} else {
printf("no file found.\n");
}
printf("\nword count: %d, char count: %d\n\n", word_count, char_count);
for (int i = 0; i < word_count; i++) {
printf("%s\n", arr[i]);
}
return (EXIT_SUCCESS);
}
這會產生以下輸出:
2082018
1200
79
Meeting
3082018
1300
60
Lunch
4082018
1400
30
Dinner
5082018
0600
90
Work
當涉及到為鍵和值對分離成單獨的字符串時,我會陷入困境。
我嘗試的第二種方法是使用fgets
,但我無法獲得任何正確的輸出:
if (inp_cal) {
printf("Processing file...\n");
while (fgets(line, sizeof line, inp_cal)) {
char KEY_arr[10];
char VAL_arr[50];
char KEY;
char VAL;
if (sscanf(line, "%29s%29s", KEY, VAL) != 2) { /* error, bad line */
printf("Bad line format\n");
} else {
KEY_arr[line_count] = KEY;
VAL_arr[line_count] = VAL;
printf("%c, %c\n", KEY_arr[line_count], VAL_arr[line_count]);
}
line_count++;
}
} else {
printf("no file found.\n");
}
有關如何改進上述方法之一以讀取4列文本文件並存儲在兩個char數組中的任何建議?
使用fscanf()
,因為您知道數據的格式,並提取一行中的每個標記。 然后,第一個標記是你的密鑰,其他三個標記是一起的,所以用snprintf()
連接它們。
例:
#include <stdio.h>
#include <string.h>
#define N 10 // max number of lines to be read
#define VALLEN 100
int main(void)
{
int key_arr[N], a, count = 0;
char val_arr[N][VALLEN], b[10], c[10], d[10];
FILE* fp;
fp = fopen("input.txt", "r");
char bb[33];
while (fscanf(fp, "%d %s %s %s", &a, b, c, d) != EOF) {
if(count < N) {
key_arr[count] = a;
snprintf(val_arr[count++], VALLEN, "%s %s %s", b, c, d);
}
}
for(int i = 0; i <count; ++i)
printf("key=%d, val = %s\n", key_arr[i], val_arr[i]);
fclose(fp);
return 0;
}
輸出:
key=2082018, val = 1200 79 Meeting
key=3082018, val = 1300 60 Lunch
key=4082018, val = 1400 30 Dinner
key=5082018, val = 0600 90 Work
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.