Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

C Programming Overview- String, Loop

Loading...

Published in: C / C++
2,643 Views

C Programming Overview-String, Loop

Akhilesh K / Lucknow

4 years of teaching experience

Qualification: M.Sc (NIT Rourkela - 2019)

Teaches: All Subjects, English, Mathematics, Science, Chemistry, Physics, Algebra, IIT JEE Mains, AIPMT, NEET

Contact this Tutor
  1. C Programming - Lecture 3 File handling in C - opening and closing. ' Reading from and writing to files. ' Special file streams stdin, stdout & stderr. ' How we SHOULD read input from the user. , What are STRUCTURES? What is dynamic memory allocation?
  2. File handling in C In C we use FILE * to represent a pointer to a file. fopen is used to open a file. It returns the special value NULL to indicate that it couldn't open the file. FILE *fptr; char filename C] " file 2 . dat " fptr= f open (filename, "w") ; if (fptr NULL) { f print f (stderr, ERROR") ; / * DO SOMETHING * /
  3. Modes for opening files The second argument of fopen is the mode in which we open the file. There are three r" opens a file for reading 'w" opens a file for writing - and writes over all previous contents (deletes the file so be careful!) a" opens a file for appending - writing on the end of the file
  4. The exit() function Sometimes error checking means we want an "emergency exit" from a program. We want it to stop dead. ' In main we can use "return" to stop. ' In functions we can use exit to do this. ' Exit is part of the std lib . h library exit (-1); in a function is exactly the same as return -1; in the main routine
  5. Writing to a file using fprintf ' fprintf works just like printf and sprintf except that its first argument is a file pointer. FILE *fptr,• fptr= f open ("file. dat" "w"); / * Check it's open * / ' using fscanf — but there is a better way.
  6. Reading from a file using fgets ' fgets is a better way to read from a file We can read into a string using fgets FILE *fptr,• char line [1000]; / * Open file and check it is open * / while (f gets (line, 1000, fptr) ! = NULL) { print f ("Read line 00 s \ n" , line) • fgets takes 3 arguments, a string, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF)
  7. Closing a file We can close a file simply using fclose and the file pointer. Here's a complete "hello files". FILE *fptr,• char filename "my file. dat" fptr= fopen (filename, "w") ; if (fptr NULL) { print f ("Cannot open file to write! \ n") exit (-1); f print f (fptr, "Hello World of filing! \ n") ; f close (fptr) ;
  8. Great Muck-Ups in C #72 of 100 We use the file pointer to close the file - not the name of the file FILE *fptr,• fptr= fopen ("my file . dat" r"); / * Read from file * / f close ("my file. dat") ; / * Ooops that's wrong * /
  9. Three special streams Three special file streams are defined in the std io . h header ' std in reads input from the keyboard ' stdout send output to the screen stderr prints errors to an error device (usually also the screen) What might this do: f print f (stdout, "Hello World! \ n") ;
  10. Reading loops ' It is quite common to want to read every line in a program. The best way to do this is a while loop using fgets. / * define MAX LEN at start using enum * / FILE *fptr; / * A line of text * / char t line CMAXLEN] ; fptr= f open ("silly file. txt " r"); / * check it's open * / while (f gets (t line, MAX LEN, fptr) / * Now do something with t line * / f close (fptr) ;
  11. Using fgets to read from the keyboard fgets and stdin can be combined to get a safe way to get a line of input from the user # include enum { MAX LEN= 1000 int main() char read line [MAX LEN] • f gets (read line, MAX LEN, std in) ; print f ("You typed 00 s" , read line) ; return 0;
  12. Getting numbers from strings Once we've got a string with a number in it (either from a file or from the user typing) we can use a toi or a tof to convert it to a number The functions are part of std I ib . h char number string [l 14 int i; double pi, pi = a tof (number string) ; i = a toi ("12") Both of these functions return 0 if they have a problem
  13. Great Muck-Ups in C #11 of 100 ' fgets includes the '\n' on the end This can be a problem - for example if in the last example we got input from the user and tried to use it to write a file: FILE *fptr,• char read fname [1000] f gets (read fname, 1000, std in) ; fptr= f open (read fname, "w") ; / * oopsie file name also has \ n * / Even experienced programmers can make this error
  14. Structures in C In C, we can create our own data types - FILE is an example of this. If programmers do a good job of this, the end user doesn't even have to know what is in the data type. struct is used to describe a new data type. typedef is used to associate a name with it. int, double and char are types of variables. With struct you can create your own. It is a new way to extend the C programming language.
  15. The struct statement Here is an example struct statement. # include struct line { int x 1, y 1; int x 2, y 2; main ( ) struct line line 1; co-ords of 1 end of line* / co-ords of other end * / This defines the variable linel to be a variable of type line
  16. Typedef ' Typedef allows us to associate a name with a structure (or other data type). Put typedef at the start of your program. typedef struct line { int x 1, y 1; int x 2, y 2; } LINE; int main() LINE linel,• linel is now a structure of line type This is what was happening with all that FILE * stuff
  17. Accessing parts of a struct ' To access part of a structure we use the dot notation LINE linel,• linel.xl= 3; linel.yl= 5; linel . x 2 if (linel.y2 print f ( ' 'Y 3) co-ord of end is 3 \ n") ;
  18. What else can we do with structs ? We can pass and return structs from functions. (But make sure the function prototype is _ AFTER declared) typedef struct line int xl,yl; int x 2, y 2; } LINE; LINE find perp line / * Function takes a perpendicular line the struct is (LINE) ; line and returns a
  19. What's the point of all this with structs ? It makes your programming easier and it makes it easier for other programmers. FILE * was a typedef'd struct but you could use it without knowing what was inside it. ' You can extend the language - for example, if you use complex numbers a lot then you can write functions which deal with complex nos.
  20. Complex no functions typedef struct comp ex { float i mag; float real; } CPLX,• CPLX mult complex int main() / * Main goes here CPLX mult complex CPLX answer; (CPLX, CPLX) ; (CPLX nol, CPLX n02) nol . imag*n02 . i mag; answer. real = nol . real*n02 . real answer. imag= nol . imag*n02 . real + nol . real*n02 . i mag; return answer;
  21. Dynamic memory allocation ' How would we code the "sieve of Eratosthenes' to print all primes between 1 and n where the user chooses n? We _ could _ simply define a HUGE array of chars for the sieve - but this is wasteful and how big should HUGE be? The key is to have a variable size array. , In C we do this with DYNAMIC MEMORY ALLOCATION
  22. A dynamically allocated sieve # include void vary sieve (int) void vary sieve (int n) / * Sieve to find all primes from 1 char *sieve; int i; sieve= (char * ) mal loc (n*sizeof (char) ) ; / * check memory here * / for (i = 0; i < n; i++) sieve [i] = UNCROSSED; / * Rest of sieve code * / / * free memory
  23. A closer look at malloc Let's look at that malloc statement again: sieve= (char * ) mall oc (n*sizeof (char) ) ; This is a CAST (remember them) that forces the variable to the right type (not needed) we want n chars sizeof(char) returns how much memory a char takes This says in effect " grab me enough memory for 'n' chars"
  24. Free The free statement says to the computer "you may have the memory back again' free ( • essentially, this tells the machine that the memory we grabbed for sieve is no longer needed and can be used for other things again. It is _ VITAL _ to remember to free every bit of memory you malloc
  25. Check the memory from malloc Like fopen, malloc returns NULL if it has a problem Like fopen, we should always check if malloc manages to get the memory. float *far ray; / * Try to allocate memory for 1000 floats * farray= mal loc (1000* sizeof (float) ) ; if (far ray NULL) { "Out of memory! \ n") • f print f (stderr, exit (-1);