Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中使用fgetc读取文件_C_Arrays_String_Scanf - Fatal编程技术网

在C中使用fgetc读取文件

在C中使用fgetc读取文件,c,arrays,string,scanf,C,Arrays,String,Scanf,我有一个包含更多行的文件,现在,我想扫描第三行,从一个字符扫描到另一个字符。这是可行的,但我无法使用(onerow)数组分配字符,只有第一个: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif

我有一个包含更多行的文件,现在,我想扫描第三行,从一个字符扫描到另一个字符。这是可行的,但我无法使用(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);
}
#包括
#包括
#包括
#包括
#如果已定义(WIN32)| |已定义(_WIN32)
#包括
#恩迪夫
内部主(空){
#如果已定义(WIN32)| |已定义(_WIN32)//用于拉丁语2
SetConsoleCP(1250);
SetConsoleOutputCP(1250);
#恩迪夫
//char*onerow=(char*)malloc(num*sizeof(char));
char*onerow[250];
字符c;
int行=3,j=0;
文件*fp;
fp=fopen(“proba.txt”、“r”);

对于(int i=0;i您声明了
onerow
作为指向字符的指针数组,您不能将字符直接分配给元素

如果希望
onerow
成为动态增长的字符串,则应将其声明为指针,而不是指针数组:

size_t rowsize = 250;
char *onerow = malloc(rowsize);
然后,如果获得的行大小超过
rowsize
个字符,则应调用
realloc()

c = fgetc(fp);
if (j >= rowsize-1) {
    rowsize += 250;
    onerow = realloc(onerow, rowsize);
}
onerow[j++] = c;
最后,在追加空字节时,不应从
j
中减去
1
,它应该是:

onerow[j] = '\0';

在上面的测试中,我在
realloc()
之前使用了
rowsize-1
,以确保有空字节的空间(而不是在这里进行另一个测试)。

onerow
是指针数组,而不是字符数组。您没有从
onerow[j++]=c;
得到警告吗?为什么不使用
fgets()
读取行数?如果没有最后一个
\n
fgetc
返回
EOF
,会发生什么情况?哦,是的,我有这个警告(现在已启用,抱歉!)一切正常,正常工作。感谢它和提示!我建议将
c
char
更改为
int
,并测试
EOF
。否则-->在没有3行换行符的文件上无限循环。OP的代码尝试读取第4行并丢弃它——因为
I