【发布时间】:2017-11-13 21:34:39
【问题描述】:
我有一个包含更多行的文件,现在,我想扫描第 3 个,从 char 到 char。这是有效的,但我不能用(onerow)数组分配字符,只有第一个:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
int main(void) {
#if defined(WIN32) || defined(_WIN32) //for latin2
SetConsoleCP(1250);
SetConsoleOutputCP(1250);
#endif
//char* onerow=(char*) malloc(num*sizeof(char));
char* onerow[250];
char c;
int row=3, j=0;
FILE *fp;
fp = fopen("proba.txt", "r");
for (int i=0; i<=row; i++) {
if(i!=row-1) { //not the row we need, jump over it
while(c!='\n')
c=fgetc(fp);
c='a'; //to make true while next time
}
if(i==row-1) {
while(c!='\n') { //this is what we need
//onerow[j]=fgetc(fp);
//onerow = (char*)realloc(onerow, ++num*sizeof(char));
c=fgetc(fp);
printf("%c", c); //this is working well (prints everyth.)
onerow[j++]=c;
}
}
}
onerow[j-1]='\0';
fclose(fp);
printf("%s", onerow); //prints only the first charachter
//free(onerow);
}
第一个输出 (%c) 很好,即整行。然而,第二个输出 (%s) 只是该行的第一个字符(这是文件中的一个数字...该文件是一个 latin2 txt。)
【问题讨论】:
-
onerow是指针数组,而不是字符数组。 -
你没有收到来自
onerow[j++]=c;的警告吗? -
为什么不用
fgets()来读行呢? -
当没有最后一个
\n和fgetc返回EOF时会发生什么? -
哦,是的,我有这个警告(现已启用,抱歉!)一切正常,工作正常。感谢它和提示!