gpt4 book ai didi

c - 使用 fgets + 动态内存分配

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:23 24 4
gpt4 key购买 nike

我有一个家庭作业问题需要帮助。我需要实现一个函数 char *getStrFromFile(FILE*);。我就是不明白。我试图弄清楚这个问题。

This function safely reads a complete line of unknown length from the open file pointed to by fpin. It returns a line that is at most CHUNKSZ-1 characters longer than the minimum needed to hold the line. It initially allocates an array of DEFLEN characters to hold the string, and if this space is inadequate to hold the string, it will iteratively create a new string that is CHUNKSZ larger, copy the old string to it release the old string, and then read in more characters from the file, and continue this until the entire line of arbitrary length can be returned.

RETURNS: NULL if no characters are left in fpin, otherwise: pointer to allocated array at most CHUNKSZ-1 characters longer than miminum necessary to hold an arbitrarily long line from file fpin

 int main(int nargs, char *args[])
{
FILE *fpin;
char *getStrFromFile(FILE*);
if (nargs != 2)
{
fprintf(stderr, "USAGE: %s <file>\n", args[0]);
exit(1);
}
fpin = fopen(args[1], "r");
while(1)
{
char *ln;
ln = getStrFromFile(fpin);
if (!ln)
break;
printf("%s", ln);
free(ln);
}
fclose(fpin);
return(0);
}

这是我必须使用的主要方法。这是我目前所知道的。

char *getStrFromFile(FILE *fpin)
{
char string[DEFLEN];
if(fgets(string, CHUNKSZ, fpin) != NULL) {
int l = lstr(string);
if(string[l-1] = '\n') {
return string;
} else {
int size = 1;
int end = 0;
while (string[l-1] != '\n') {
size += CHUNSZ;
char *s2 = (char*)malloc(sizeof(char)+size);
for(i = 0+end; i < lstr(string); i++) {
s2[i] = string[i];
}
end += lstr(string);
fgets(string, size + end, fpin);
return s2;

最佳答案

这是不正确的。

if(string[l-1] = '\n')

一定是

if(string[l-1] == '\n')

关于c - 使用 fgets + 动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13134193/

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