Thread: How to create a FILE?newbie question..

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    31

    How to create a FILE?newbie question..

    hi all,

    Im planning to use FILE to set up a student database.May i know how do i create the text file(Eg:student.txt)?
    It seems that i just have to type all the info in a text editor and save as .txt file.How must I arrange the info and link it to my program?

    I've read notes and also searched the website, but all i get is teaching me how to read and write from a file but not creating that .txt file.

    Thanx for ya time!

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    I've read notes and also searched the website, but all i get is teaching me how to read and write from a file but not creating that .txt file.
    If you open a file for writing and it gets created. Look up fopen in your man/help pages.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User vinit's Avatar
    Join Date
    Apr 2006
    Location
    India
    Posts
    39
    I have 1 small program which has all file operation,However I've used binary mode for files.
    Use binary mode files instead of .txt.Binary files are far more better than ordinary text file.
    File modes
    rb = binary read
    wb = binary write
    ab = append binary
    heres my code compiled with gcc 3.4 on linux but functions are same across windows & linux

    Code:
     
    #include <stdio.h>
    struct rec {
     int roll,t;
    };
    	
    int main()
    {
      struct rec r;
      FILE *fp;
      int i,j;
    
    
      fp=fopen("abc.dat","wb+"); /* open file in read & write mode  u              
                                                       can use ab+ also */
      if(fp==NULL) {
    	  printf("\nError opening file");
    	  return -1;
      }
    /* this part writes in file */
      for(i=0;i<5;i++) {
        r.roll = i + 1;
        r.t = 0;
        fwrite(&r,sizeof(r),1,fp); /* write to file */
      }
    /* till here */
      rewind(fp);
      while(1) {
    	  if(feof(fp))
    		  break;
    	  fread(&r,sizeof(r),1,fp);
    	  if(r.roll == 2) {
                 printf("\nStudent with rollno %d found",r.roll);
    	      break;
    	   }
      } 	   
    /* This part reads from file & prints*/
     rewind(fp);
      for(i=0;i<5;i++) {
        fread(&r,sizeof(r),1,fp);  /* read from file */
        printf("\nRoll = %d , t = %d",r.roll,r.t);
      }
    /* till here */
      fclose(fp); /* close file */
    }
    Last edited by vinit; 04-12-2006 at 03:05 AM.

  4. #4
    Registered User
    Join Date
    Sep 2005
    Posts
    31
    Hi vinit...thanks for da reply!

    For my student database which consist :
    Student name,ID,Year of degree,Major,Courses name and id,total credit hours,Grades for each course,GPA,Dean's list.

    Is is okay if i use text file(.txt)?Coz im a newbie and im not really sure how to use binary files.

    Actually my question is :How do i put all those student info above into my database?
    Do i have to input it through my program by using the fwrite function?Or i just create a .txt file and type all the info in it, then i can just open it with my program to read later?

    sorry to make u confused with my questions, hope someone can understand me here....

  5. #5
    Registered User vinit's Avatar
    Join Date
    Apr 2006
    Location
    India
    Posts
    39
    sherwi, please go through code that I've posted.
    Try to understand it.Its very basic code,learn it u'll get ur answers by yourself.
    Do i have to input it through my program by using the fwrite function?Or i just create a .txt file and type all the info in it, then i can just open it with my program to read later?
    No Thats not the way to create file,create file using fopen(),get all data from set of scanf statement in structure & then write it to file using fwrite().Go through the code its very basic & u must read file I/O in C before coding,if you are not able to understand it then its really difficult for everyone to help u here.
    Last edited by vinit; 04-12-2006 at 05:17 AM.

  6. #6
    Registered User
    Join Date
    Sep 2005
    Posts
    31
    ok, i'll try then..thanx for the codes !

    If it okay if i don't use scanf statements to get all the data?Instead i just initialize all the data in structure and write it to a file.Will it work the same?

    Also, how can i open that binary file that i've created to view?I wont see anything if i open a binary file using a text editor right?

  7. #7
    Registered User vinit's Avatar
    Join Date
    Apr 2006
    Location
    India
    Posts
    39
    It is ok if u initialise all parameters & then write to file,but then for that u've to create that much large array.Instead u can us 1 variable of ur structure & 1 loop to put many records in files.So its on u which way u like.

    To view binary files U'll need hex editor which are freely available on net.

  8. #8
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    You can write anything to a file: random strings, user input, hardcoded values. If you work with binary files, use fread() and fwrite(); if you want to read from plain text files use fprintf(), fscanf() and fgets(). Reading from plain text is arguably easier, but more space might be required, and you will need to do some basic error handling. Doing it in binary gives you full control, but don't expect to be able to edit your records reasonably easily in Notepad.

    If you open a binary file in Notepad, it depends on what you've stored. It could simply be jumbled-looking English; or you could be staring at a whole lot of plain rubbish, especially if you write raw struct data or something, using, say, pointers.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

  9. #9
    Registered User
    Join Date
    Sep 2005
    Posts
    31
    Instead u can us 1 variable of ur structure & 1 loop to put many records in files
    Erm...i don't quite understand what u mean by this.Mind to explain?thanx

  10. #10
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Instead u can us 1 variable of ur structure & 1 loop to put many records in files


    Erm...i don't quite understand what u mean by this.Mind to explain?thanx
    And in English please --

  11. #11
    Registered User
    Join Date
    Sep 2005
    Posts
    31
    Code:
    #include <stdio.h>
    
    struct A{
    	char name[50];
    	char id[8];
    	char year[8];
    	char grade[3];
    };
    
    struct Record{
    	char name[30];
    	long int id;
    	char year[8];
    	char major[20];
    	struct A course[6];
    	int credit_hours;
    	float gpa;
    	char deanlist[4];
    };
    
    int main()
    {
    struct Record student[13];
    FILE *infile;
    int i,j;
    
    for(i=0;i<13;i++){
    	printf(“Please enter student info\n”);
    
    	scanf(“%s %ld %s %s %d %f 
    %s”,student[i].name,&student[i].id,student[i].year,student[i].major,&student[i].credit_hours,&student[i].gpa,student[i].deanlist);
    
    for(j=0;j<6;j++){
    	printf("Please enter course info\n");
    	
    scanf("%s%s%s%s",student[i].course[j].name,student[i].course[j].id,student[i].course[j].year,student[i].course[j].grade);
    	}
    }
    
    if((infile=fopen("student.txt","w"))==NULL)
    	printf("Error\n");
    else{
    	for(i=0;i<13;i++){
    		
    fprintf(infile,"%s%ld%s%s%d%.2f%s",student[i].name,student[i].id,student[i].year,student[i].major,student[i].credit_hours,student[i].gpa,student[i].deanlist);
    
    	for(j=o;j<6;j++){
    		
    fprintf(infile,"%s%s%s%s",student[i].course[j].name,student[i].course[j].id,student[i].course[j].year,student[i].course[j].grade);
    		}
    }
    
    fclose(infile);
    }
    
    return 0;
    
    }
    This is what i've come up with.Is this the right way?But when i run it, it looks abit weird, i dunno if it's correct.
    Btw, i used text files here.Coz i dunno how binary files can be used with search later in my search and sort program.

    Note:The second for loop is to include the data for struct A course.

  12. #12
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    Since you are using scanf you are going to have to deal with the newline character left over between each scanf call.
    Probably better to use fgets and parse the line with sscanf.
    You should also check the return codes of your input functions.


    Would be much more usable if you prompted for each part individually.


    Code:
    for(j=o;j<6;j++){
    When you write to the file you need to at least separate each piece of data by a space so you can read it back in.
    Newlines for each record as well.


    Formatting like this may be more readable
    Code:
        scanf("%s %s %s %s" ,student[i].course[j].name
                            ,student[i].course[j].id
                            ,student[i].course[j].year
                            ,student[i].course[j].grade);
    Last edited by spydoor; 04-13-2006 at 09:48 AM.

  13. #13
    Registered User
    Join Date
    Sep 2005
    Posts
    31
    Thanks spydoor..
    Code:
    #include <stdio.h>
    
    struct A{
            char name[50];
            char id[8];
            char year[8];
            char grade[3];
    };
    
    struct Record{
            char name[30];
            long int id;
            char year[8];
            char major[20];
            struct A course[6];
            int credit_hours;
            float gpa;
            char deanlist[4];
    };
    
    int main()
    {
    struct Record student[13];
    FILE *infile;
    int i,j;
    
    
    for(i=0;i<13;i++){
            printf("Please enter student info\n");
    	
    	fgets(student[i].name,30,stdin);
    	scanf("%ld %s %s %d %f %s",&student[i].id
    				  ,student[i].year
    				  ,student[i].major
    				  ,&student[i].credit_hours
    				  ,&student[i].gpa
    				  ,student[i].deanlist);
    
    
    for(j=0;j<6;j++){
            printf("Please enter course info\n");
    	
    	fgets(student[i].course[j].name,50,stdin);
    	scanf("%s %s %s",student[i].course[j].id
    			,student[i].course[j].year
    			,student[i].course[j].grade);
            }
    }
    
    if((infile=fopen("student.txt","w"))==NULL)
            printf("Error\n");
    else{
            for(i=0;i<13;i++){
    
    		fprintf(infile,"%s %ld %s %s %d %.2f %s",student[i].name
    						  	,student[i].id
    						  	,student[i].year
    						  	,student[i].major
    						  	,student[i].credit_hours
    						  	,student[i].gpa
    						  	,student[i].deanlist);
    
            for(j=0;j<6;j++){
    
    		fprintf(infile,"%s %s %s %s",student[i].course[j].name
    					    ,student[i].course[j].id
    					    ,student[i].course[j].year
    					    ,student[i].course[j].grade);
                    }
    }
    
    fclose(infile);
    }
    
    return 0;
    
    }
    Okay, i've changed to fgets to get a string of name for both loops.I think it works for the first loop, but not for the second loop.I can only enter 3 data instead of 4 data.Also, how to parse with sscanf?

    One more question, for the second loop(course info), not every student will be taking 6 courses.They can be taking less than that,maybe 3 or 4 courses only.How can i stop the loop when i've entered enough amount of courses taken by the student?

    Thanks alot for checking my codes here, u guys help me lots!

  14. #14
    Registered User
    Join Date
    Sep 2005
    Posts
    31
    Can anyone help me ?plssss....thank you so much

  15. #15
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Code:
    for(j=0;j<6 & ch=='Y';j++)
    {
        printf("Please enter course info\n");
    	
    	fgets(student[i].course[j].name,50,stdin);
    	fgets(student[i].course[j].id,8,stdin);
    	fgets(student[i].course[j].year,8,stdin);
    	fgets(student[i].course[j].grade,3,stdin);
        clear_buffer();
        
    	printf("Want to enter Course ( Y / N)\n");
    	ch = getchar();
    }	
    
     --------- > clear_bufer fucntion < ---------
    
    void clear_buffer(void)  // function to cleae the input buffer. NOTE: read FAQ
    {
         int ch;
         while((ch=getchar())!='\n' && ch!=EOF);
    }
    ssharish2005

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie Question - fflush(stdin) & fpurge(stdin) on Mac and PC
    By tvsinesperanto in forum C Programming
    Replies: 34
    Last Post: 03-11-2006, 12:13 PM
  2. Question about binary trees and files
    By satory in forum C Programming
    Replies: 9
    Last Post: 03-06-2006, 06:28 AM
  3. another exercise question
    By luigi40 in forum C# Programming
    Replies: 3
    Last Post: 11-28-2005, 03:52 PM
  4. Question type program for beginners
    By Kirdra in forum C++ Programming
    Replies: 7
    Last Post: 09-15-2002, 05:10 AM
  5. I have a Question about memory usage for C.
    By bobthefish3 in forum C Programming
    Replies: 34
    Last Post: 12-24-2001, 04:37 PM