【发布时间】:2016-11-02 22:00:40
【问题描述】:
所以我使用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;
}
【问题讨论】:
标签: c arrays file pointers scanf