My entry in C. It doesn't check for errors when opening the file.
PHP Code:
/* Beginner Programming Challenge 2
Write a program that reads bhaarat.text, and takes the languages that begin
with "H" or "S" and writes them to another file, named "out.text". The output
can be more flexible. Then have this program write "23. English" to the end
to continue the list in bhaarat.text. */
#include <stdio.h>
#include <stdlib.h>
/* Remove all numbers, punctuations and spaces from the string. */
void rem_nums(char *string)
{
const char *src = string;
char *dst = string;
do {
while (*src == '0'
|| *src == '1'
|| *src == '2'
|| *src == '3'
|| *src == '4'
|| *src == '5'
|| *src == '6'
|| *src == '7'
|| *src == '8'
|| *src == '9'
|| *src == '.'
|| *src == ' ')
++src;
} while ((*dst++ = *src++) != '\0');
}
/* Opens bhaarat.text and while it hasn't reached the end of the file. For each
line it reads, it removes the numbers and punctuations and checks if the
first letter is S or H. If this is the case, the language name is appended to
out.text.
Finally it appends '23. English' to bhaarat.text. */
int main()
{
char *input_file = "bhaarat.text";
char *output_file = "out.text";
char file_input[50];
FILE *read_append;
FILE *append;
read_append = fopen(input_file, "r+a");
while(fgets(file_input, 50, read_append) != NULL) {
rem_nums(file_input);
if(file_input[0] == 'H'
|| file_input[0] == 'S') {
append = fopen(output_file, "a");
fputs(file_input, append);
fclose(append);
}
}
fputs("\n23. English", read_append);
fclose(read_append);
return 0;
}
While making this I tried to write a function, which would assign a filepointer to fopen(). If it returned NULL, the program should print an error message:
PHP Code:
#include <stdio.h>
#include <stdlib.h>
void openfile(FILE *f, char *filename, char *fileop)
{
if((f = fopen(filename, fileop)) == NULL) {
puts("Error.");
exit(1);
}
}
int main()
{
FILE *f;
openfile(f, "filename.txt", "r");
fclose(f);
return 0;
}
It works fine, when an error is occuring. However if the file exists the program crashes.
Bookmarks