11-Pointers and Files
11-Pointers and Files
11/22/2022 2
Strings
11/22/2022 3
Addresses and Pointers ( a brief)
■ int j = 5;
■ The unary operator & gives the address of its
operand.
■ Hence, &j is the address of j
■ & cannot be applied to expressions, constants, or
register variables.
■ Let &j be 1000.
■ Even by knowing this 1000, if you do not know that
the value at the address is an integer, you can not
retrieve 5.
■ So, along with address, we need the type of the
value located at the address.
Pointers
x Name
ip
1000 1 Value
1024 1000 Address
Pointers
❑ void swap (int *, int *);
main( )
■Thisis the correct
{
int j = 10, k = 20; way of writing a swap
swap(&j, &k); function.
printf(“%d %d”, j, k);
}
void swap(int *a, int *b)
{
int t;
t = *a, *a = *b, *b = t;
}
Pointers and Arrays
ip = a;
ip[0] = 10; /* is same as a[0] = 10 */
*(ip + 5) = 20; /* same as ip[5] = 20 */
▪ When you say, ip + 5 it is indeed ip +5*sizeof(int)
This is called pointer (address) arithmetic.
Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
FILE *fptr;
ptr = fopen("fileopen","mode");
fopen("E:\\cprogram\\newprogram.txt","w");
mode can be w, a, r,
int fputc(int char, FILE *pointer)
int main()
{
int i = 0;
FILE *fp = fopen("output.txt","w");
if (fp == NULL)
return 0;
char string[] = "good bye", received_string[20];
for (i = 0; string[i]!='\0'; i++)
fputc(string[i], fp);
fclose(fp);
fp = fopen("output.txt","r");
fgets(received_string,20,fp);
printf("%s", received_string);
fclose(fp);
return 0;
}
The fprintf( ) function is used to write set of
characters into file.
int fprintf(FILE *stream, const char *format [, argument, ...])
#include <stdio.h>
main()
FILE *fp;
}
The fscanf( ) function is used to read set of characters from file.
It reads a word from the file and returns EOF at the end of file.
int fscanf(FILE *stream, const char *format [, argument, ...])
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
1. fgetc()– This function is used to read a single character from the file.
2. fgets()– This function is used to read strings from files.
3. fscanf()– This function is used to read formatted input from a file.
#include <stdio.h>
#include <string.h>
// Driver code
int main()
{
FILE* ptr;
char ch;
ptr = fopen("test.txt", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
do {
ch = fgetc(ptr);
printf("%c", ch);
} while (ch != EOF);
fclose(ptr);
return 0;
}
{
FILE *fptr;