gpt4 book ai didi

c - 在 C 中使用 fgetc 从文件中读取

转载 作者:行者123 更新时间:2023-11-30 19:32:16 24 4
gpt4 key购买 nike

我有一个包含更多行的文件,现在我想扫描第三个字符,从一个字符到另一个字符。这是有效的,但我无法使用(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 成为动态增长的字符串,则应将其声明为指针,而不是指针数组:

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 以确保有空字节的空间(而不是在这里进行另一个测试)。

关于c - 在 C 中使用 fgetc 从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com