0

我在从另一个文件中读取字符串并将其存储到数组时遇到了一些麻烦。我需要一个指向该数组的指针,以便我可以在整个程序中使用它。所有变量都是全局的。请帮助修复 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
4

1 回答 1

1

是不是因为你的fscanf不包括\n角色?尝试:

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

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


为了删除末尾的新行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);
于 2013-06-22T04:28:32.250 回答