C File Handling Programs
C File Handling Programs
int main() {
FILE *fp = fopen("file1.txt", "w");
if (fp != NULL) {
fprintf(fp, "Hello, World!");
fclose(fp);
}
return 0;
}
int main() {
char ch;
FILE *fp = fopen("file1.txt", "r");
if (fp != NULL) {
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
}
return 0;
}
3. Append to a File
#include <stdio.h>
int main() {
FILE *fp = fopen("file1.txt", "a");
if (fp != NULL) {
fprintf(fp, "\nAppended line.");
fclose(fp);
}
return 0;
}
4. Count Characters in a File
#include <stdio.h>
int main() {
char ch;
int count = 0;
FILE *fp = fopen("file1.txt", "r");
if (fp != NULL) {
while ((ch = fgetc(fp)) != EOF)
count++;
fclose(fp);
printf("Total characters: %d\n", count);
}
return 0;
}
int main() {
char ch;
FILE *src = fopen("file1.txt", "r");
FILE *dest = fopen("copy.txt", "w");
if (src != NULL && dest != NULL) {
while ((ch = fgetc(src)) != EOF)
fputc(ch, dest);
fclose(src);
fclose(dest);
}
return 0;
}
int main() {
FILE *fp = fopen("file1.txt", "r");
int count = 0;
char ch, prev = ' ';
if (fp != NULL) {
while ((ch = fgetc(fp)) != EOF) {
if (isspace(ch) && !isspace(prev))
count++;
prev = ch;
}
if (!isspace(prev)) count++;
fclose(fp);
printf("Total words: %d\n", count);
}
return 0;
}
7. Rename a File
#include <stdio.h>
int main() {
if (rename("file1.txt", "renamed.txt") == 0)
printf("File renamed successfully.\n");
else
perror("Error renaming file");
return 0;
}
8. Delete a File
#include <stdio.h>
int main() {
if (remove("file_to_delete.txt") == 0)
printf("File deleted successfully.\n");
else
perror("Error deleting file");
return 0;
}
int main() {
FILE *fp = fopen("numbers.txt", "w");
if (fp != NULL) {
for (int i = 1; i <= 5; i++)
fprintf(fp, "%d\n", i);
fclose(fp);
}
fp = fopen("numbers.txt", "r");
int num;
while (fscanf(fp, "%d", &num) != EOF)
printf("%d ", num);
fclose(fp);
return 0;
}
int main() {
char line[256];
FILE *fp = fopen("file1.txt", "r");
if (fp != NULL) {
while (fgets(line, sizeof(line), fp))
printf("%s", line);
fclose(fp);
}
return 0;
}