Skip to main content

Posts

Showing posts with the label C

File Input/output in C

Input and output to and from files is identical to that at the command line, except the fprintf and fscanf functions are used and they require another argument. This additional argument is called a file pointer. In order to write two floating point numbers to a file, you first need to declar the file pointer with the FILE type, and you need to open it, as in float x=1, y=2; FILE *file; file = fopen(‘‘file.txt’’,’’w’’); fprintf(file,’’%f %f\n’’,x,y); fclose(file); The function fprintf is identical to the printf function, except now we see it has another argument file, which is a pointer to the file. Before you use the file variable, you need to open the file with file = fopen(‘‘file.txt’’,’’w’’); This opens up the file ‘‘file.txt’’ and the ‘‘w’’ which is the mode and indicates how the file will be used. The following three modes are allowed: Mode String Open for reading “r” Open for writing “w” Open and append “a” When you are done with the file, you close it ...

Defining your own types

C allows you to define your own types, and this can make your codes much more legible. For example, you can define a type called price that you can use to define variables that you use to represent the price of certain objects. To do so, you would use typedef float price; int main(void) { price x, y; } The typedef is used in the following way: typedef existing_type new_type; The price type example is identical to using float x, y; but it is useful to use typedef when you would like the ability to change the types of certain variables throughout your codes by only changing one line. That is, if you wanted to change all of your prices to type double, then you would only need to change the typedef line to typedef double price;

Basic structure of a C program

As we saw in the hello.c example in the last lecture, Every C program must contain a main function , since the main function is the first function called when you run your program at the command line. In its simplest form, a C program is given by int main(void) { printf(‘‘Hello world!\n’’); } The int stands for the “return type”, which says that the main function returns an integer if you tell it to do so. We will get into more detail with functions and return types, but you can return a number to the command line with the return function in C, as in int main(void) { printf(‘‘Helloworld!\n’’); return 2; }