c read file code example

Example 1: read files in c

#include<stdio.h>
int main(){
	FILE *in=fopen("name_of_file.txt","r");
	char c;
	while((c=fgetc(in))!=EOF)
		putchar(c);
	fclose(in);
	return 0;
}

Example 2: c write to file

#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[1000];

    // creating file pointer to work with files
    FILE *fptr;

    // opening file in writing mode
    fptr = fopen("program.txt", "w");

    // exiting program 
    if (fptr == NULL) {
        printf("Error!");
        exit(1);
    }
    printf("Enter a sentence:\n");
    fgets(sentence, sizeof(sentence), stdin);
    fprintf(fptr, "%s", sentence);
    fclose(fptr);
    return 0;
}

Example 3: how to take inputs and give outputs from a file in c

#include<stdio.h>

int main()
{
    FILE *fp;
    char ch;
    fp = fopen("one.txt", "w");
    printf("Enter data...");
    while( (ch = getchar()) != EOF) {
        putc(ch, fp);
    }
    fclose(fp);
    fp = fopen("one.txt", "r");
 
    while( (ch = getc(fp)! = EOF)
    printf("%c",ch);
    
    // closing the file pointer
    fclose(fp);
    
    return 0;
}

Example 4: c file

#include <stdio.h>
#include <stdlib.h>

int main() {
   	printf("Hello Word!");
    return 0;
}

Example 5: c read file content

char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");

if (f)
{
  fseek (f, 0, SEEK_END);
  length = ftell (f);
  fseek (f, 0, SEEK_SET);
  buffer = malloc (length);
  if (buffer)
  {
    fread (buffer, 1, length, f);
  }
  fclose (f);
}

if (buffer)
{
  // start to process your data / extract strings here...
}

Example 6: c read file from command line

You can use as your main function:
int main(int argc, char **argv) 

So, if you entered to run your program:
C:\myprogram myfile.txt

argc will be 2
argv[0] will be myprogram
argv[1] will be myfile.txt

To read the file:
FILE *f = fopen(argv[1], "r");