gpt4 book ai didi

c - 从文件读取字符串时出错

转载 作者:行者123 更新时间:2023-11-30 15:47:40 25 4
gpt4 key购买 nike

我在从另一个文件读取字符串并将其存储到数组时遇到一些问题。我需要一个指向该数组的指针,以便我可以在整个程序中使用它。所有变量都是全局的。请帮助修复 fgets 行以解决此问题。谢谢!

#include <stdio.h>
#include <stdlib.h>

void load_data();

int value;

char name[25];
char * nameP = NULL;

char another_name[25];
char * another_nameP = NULL;

int main()
{
load_data();

printf("value = %i\n", value);
printf("name = %s\n", name);
printf("another name = %s\n", another_name);

return 0;
}
void load_data()
{
FILE * fileP;

if (!(fileP = fopen ("save_file.dat", "rt")))
{
printf("\nSave file \"save_file.dat\" not found.\n");
printf("Make sure the file is located in the same folder as the executable file.\n\n");
exit(1);
}
rewind(fileP);
fscanf (fileP, "%i", &value);
fgets (name, 25, fileP); // what is wrong with this line?
fgets (another_name, 25, fileP); // what is wrong with this line?

nameP = name;
another_nameP = another_name;
}

save_file.dat 的内容:

30
This is my name
This is another name

最佳答案

也许是因为你的fscanf不包括\n特点?尝试:

fscanf(fileP, "%i\n", &value);

由于您没有读取换行符,因此您的 fgets (在下一行)只需继续阅读,直到找到 EOF\n 。在这种情况下,它立即找到 \n字符,因此它停止读取。因此,文件的第三行永远不会被读取。

<小时/>

为了删除 fgets 末尾的新行,只需添加一个函数即可:

void remove_newline(char *str) {
size_t len = strlen(str);
if (str[len-1] == '\n') {
str[len-1] = '\0';
}
}

记住#include <string.h> 。然后,在打印数据之前,只需调用:

remove_newline(name);
/* ... */
printf("name = %s\n", name);

关于c - 从文件读取字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17247261/

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