[英]How to use fscanf to put strings into an array?
因此,我正在使用fscanf
來讀取文件,並且正在嘗試將這些字符串放入數組中。 看來可行,但是我只將最后一個字符串放入數組中。 當我嘗試打印時,我只打印我最后一個字符串的字符。 我沒有包括我的方法,因為它不會影響fscanf
功能,以防萬一有人感到困惑。 另外,我的CMDLINE文件具有以下字符串foo barr tar 526-4567 456-8792
。
輸出是:
456-8792
56-8792
6-8792
等等...
2
這是代碼:
int main (int argC, char *argV[]) {
FILE *fp;
int index;
int ret;
char str[1000];
//Need at least 2 files to begin program
if (argC < 3) {
fprintf(stderr, "Usage: %s file\n", argV[0]);
exit(1);
}//if statemtn
//check to see if the CMDLINE file is in the arguements
ret = scanC(argC, argV);
//if no CMDLINE file is found, print error and exit
if (ret == 1) {
fprintf(stderr, "you must provide a CMDLINE file\n");
exit(1);
}
//iterate and open CMDLINE file and read from it
for (index = 0; index < argC; index++) {
if (strcmp(argV[index], "CMDLINE") == 0) {
fp = fopen(argV[index], "r");
//error check
if (fp == NULL) {
fprintf(stderr, "Counld not open file %s\n", argV[index]);
exit(1);
}//if statment
//read from fscanf and put it's arguements into an array
while (!feof(fp)) {
char *p2 = str;
//scan the strings of the file into str array
while (fscanf(fp, "%s", p2) != EOF) {
p2++;
}//while loop 2
}//while lop 1
//close the file for it is not needed to be open anymore
fclose(fp);
}//if statement
}//for looop
char *p;
p = str;
int j;
for (j = 0; j < strlen(str); j++) {
printf("%s\n", p);
p++;
}
return 1;
}
char *p;
p = str;
int j;
for (j = 0; j < strlen(str); j++)
{
printf("%s\n", p);
p++;
}
您只有一個字符串,例如"abcd"
,您可以將其打印為printf("%s\\n", str);
而是從不同的偏移量開始打印相同的字符串。 結果如下:
abcd
bcd
cd
d
也許您對“字符數組”和“字符串數組”感到困惑
//This will reserve 100 character arrays, or 100 strings
char *arr[100];
int count = 0;
while (fscanf(fp, "%999s", str) == 1)
{
arr[count] = malloc(strlen(str) + 1);
strcpy(arr[count], str);
count++;
if (count == 100)
break;
}
int i;
for (i = 0; i < count; i++)
printf("%s\n", arr[i]);
在實際的應用程序中,您可以使用malloc
和realloc
分配足夠大的字符串數組以讀取文件。
您可以使用標記來設置“當前字符”:
char *p2 = str;
size_t k = 0;
size_t pos = 0;
//scan the strings of the file into str array at position pos
while((k = fscanf(fp, "%s", p2 + pos)) != EOF){
// update pos
pos += k;
p2++;
}//while loop 2
這將使您可以將整個文件存儲在您的字符串中(只要少於1000個字符)! 否則,只需在while循環中添加防護措施即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.