Takahiro Waki
0
Q:

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;
}
4
#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;
}
4
#include<stdio.h>
int main(){
	FILE *out=fopen("name_of_file.txt","w");
	fputs("Hello File",out);
	fclose(out);
	return 0;
}
4
#include <stdio.h>

int main() {
  	char contents[3000];
	FILE *fp = fopen("filename.txt", "r");
	fscanf(fp, "%s", contents);
  	printf(contents);
}
0
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");
0

New to Communities?

Join the community