fscanf C让#34;程序停止工作"

时间:2017-11-22 16:16:28

标签: c scanf codeblocks

我正在了解"NoLabelFeedback"extension Array { func elementIndexes<T>() -> [Int] { // if element is kind of class "T" add it to array [T] and then return } } 。我写了简单的程序:

fprintf

fscanf出现错误,显示窗口,&#34;程序停止工作&#34;。文件是在Proberly中创建的,它有&#34; test&#34;里面的文字。

我不知道它有什么不对。我正在使用Codeblocks

3 个答案:

答案 0 :(得分:2)

问题

  • 您正在阅读未经阅读许可的文件
  • 在写文件结束时。指针位于文件的末尾

解决方案

  • 使用w+
  • 打开具有读写权限的文件
  • 使用rewind(fp)
  • 将文件指针倒回到文件的开头

代码

int main()
{
    char t[20];
    FILE *fp;
    fp=fopen("a.txt","w+");
    fprintf(fp,"test");
    rewind(fp);
    fscanf(fp,"%s", t);
    printf("%s", t);
    fclose(fp);
    return 0;
}

注意:

  • 您应该检查文件是否已成功打开。

    if(fp=fopen("a.txt","w+"))
    {
       . . . 
    }
    

答案 1 :(得分:0)

你想要这个:

int main() {  
    char t[20];
    FILE *fp;
    fp = fopen("a.txt", "w+");   // open in read/write mode
    fprintf(fp, "test");
    fseek(fp, 0, SEEK_SET);      // rewind file pointer to the beginning of file
    fscanf(fp, "%s", t);
    printf("%s", t);
    fclose(fp);
    return 0;
  }

该计划仍然不好,因为:

  1. fopen
  2. 没有错误检查
  3. 缓冲区可能会溢出,fscanf(fp, "%19s", t)会更合适

答案 2 :(得分:0)

您已在写入模式下打开文件。当您尝试使用fscanf函数从中读取时会出现问题。写入文件后,将其关闭并以读取模式重新打开。

#include<stdio.h>

int main() {
     char t[20];
     FILE *fp;
     fp=fopen("a.txt","w");
     fprintf(fp,"test");
     fclose(fp);
     fp=fopen("a.txt","r");
     fscanf(fp,"%s", t);
     printf("%s", t);
     fclose(fp);
     return 0;
}
相关问题