confused by C syntax

i'm new at c.. and still having trouble at the syntax, hope you can help me... cause i'm stuck at this code

#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();
}

thanks guys...

Answers


if you have an existing file... and your file has data on it. then you could check if the data you typed is existing on the file or not. i'm not sure if this is what you want.

example if you typed... love and the file also contains the exact word... love (on one line) then it will print "success".

if the data you typed is not existing on the file, it will be appended on the file (on the next line).

int main(void){

 char arr[5];
 char arr2[5];
 int i;
 int n=0;

 FILE *stream = NULL;
 FILE *append = NULL;
 stream = fopen("studentinfo.txt", "rt");
 append = fopen("studentinfo.txt", "a+");

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

 while(!feof(stream)){ 
    fgets(arr, 6, stream);
    if(strcmp(arr, arr2)==0){
       printf("success");
    } else n=-1;  
 }  
 if (n==-1){
     fprintf(append, "%s\n", arr2);
 }
 fclose(stream);
 fclose(append);
 system("pause");
}

  1. You're opening studentinfo.txt for appending, but then reading from it (and you don't check the open succeeded
  2. you've allocated 5 characters for arr, but read up to 100 characters into it with the fgets. This will overflow and cause memory corruption
  3. you've allocated 5 characters for arr2, but read an arbitary number of characters into it - this will overflow and cause memory corruption
  4. Fgets reads characters into memory starting at arr. arr[0] is the first character. &arr[0] is the same as arr
  5. What's the getch() at the end for?
  6. Also, "a+" positions the stream at the end of the file, so you won't be able to read anything.

Need Your Help

Java GUI Rotation and Translation of Rectangle

java swing rotation awt java-2d

I am trying to draw a rectangle in JPanel that would translate and then rotate itself to mimic the movement of a car. I have been able to make the rectangle translate and rotate, however it rotates

Creating an object.cshtml editor template with MVC and Razor

asp.net-mvc razor

I am looking to create an editor template for Object.cshtml to change the behavior of the Html.EditorForModel() method. I can't find any example of this using Razor. I have seen this example using ...