从文件中读取字符串时出错

时间:2013-06-22 04:18:31

标签: c

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

1 个答案:

答案 0 :(得分:1)

可能是因为您的fscanf不包含\n字符吗?试试:

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

由于您没有阅读换行字符,因此fgets(在下一行)只会继续阅读,直至找到EOF\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);