被C语法搞糊涂了

iam*_*ice 0 c syntax

我是新来的...但仍然在语法上遇到麻烦,希望你能帮助我...因为我坚持这个代码

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

int main(void){
     FILE *stream = NULL;
     stream = fopen("studentinfo.txt", "a+");
     /*some of initialization were used for testing purposes only*/

     char arr[5];
     char arr2[5];
     int i;
     char name[3];
     char course[5];

     printf("enter details: ");
     scanf("%s", arr2);

     while(!feof(stream)){ 
        fgets(arr, 100, stream);//i am confused if the line capture was stored at arr[0]
        if(strcmp(arr, arr2)==0){//i want to compare
           printf("success");//testing
        }
        printf("%s", arr);//i wonder does fgets just overwrites the new line to arr[0]
     }

     fclose(stream);

     getch();
}
Run Code Online (Sandbox Code Playgroud)

多谢你们...

The*_*aul 6

  1. 您正在打开studentinfo.txt进行追加,但随后从中读取(并且您不会检查打开是否成功
  2. 你为arr分配了5个字符,但是用fgets读取最多100个字符.这将溢出并导致内存损坏
  3. 你已经为arr2分配了5个字符,但是在其中读取了一个任意数量的字符 - 这会溢出并导致内存损坏
  4. Fgets从arr开始将字符读入内存.arr [0]是第一个字符.&arr [0]与arr相同
  5. 最后的getch()是什么?
  6. 此外,"a +"将流定位在文件的末尾,因此您将无法读取任何内容.