Ok so i tried a few different solutions, including your swoopy, both worked with a printf, but my problem is that the function has to return a char* to the start of the line stored in the buffer, so that it can be printed via fprintf to a file. It is only allowed FILE* as an argument.
So for the function I have to take in the FILE*, create a buffer with nominal size(I'll have to work out a malloc for it later to be dynamic) inside the function, then getc form the FILE* into the buffer including the new line, then return a pointer to the buffer so it can be written to the second empty file.
Maybe I should make the buffer a global variable for the moment, I think the local variable in the function is probably destroyed upon return.
BTW here are my experiments so far:
Code:
*Libraries*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*Function prototypes*/
FILE *safe_open (char*, char*);
void print_line(FILE*);
int
main (int argc, char **argv) {
/*Main*/
FILE *file1;
FILE *file2;
file1= safe_open(argv[1],"r");
file2= safe_open(argv[2],"w");
print_line(file1);
fclose(file1);
fclose(file2);
return 0;
}
/*Functions*/
void print_line(FILE *file) {
FILE *fp = file;
int i = 0 ;
char c;
char buffer[100];
while ((c = getc(fp)) != EOF) {
buffer[i++] = c;
}
if (c == '\n') {
buffer[i++] = c;
}
buffer[i] = '\0';
for (i=0; i<100; i++) {
printf("%c", buffer[i]);
}
putchar('\n');
}
FILE *safe_open (char *file_name, char *mode)
{
FILE *fp;
if ((fp = fopen (file_name, mode)) == NULL)
{
fprintf (stdout, "Could not open file: %s\n", file_name);
exit (EXIT_FAILURE);
}
return fp;
}
output:
Code:
./simple_test2 file1.txt file2.txt
Hello This is a test to see if the get line funstion works.
���������ކ
and
Code:
/*Libraries*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*Function prototypes*/
FILE *safe_open (char*, char*);
void get_line(FILE*, char*);
int
main (int argc, char **argv) {
/*Main*/
FILE *file1;
FILE *file2;
char line[200];
int i;
file1= safe_open(argv[1],"r");
file2= safe_open(argv[2],"w");
get_line(file1, line);
for (i=0; i<200; i++) {
printf("%c", line[i]);
}
putchar('\n');
fclose(file1);
fclose(file2);
return 0;
}
/*Functions*/
void get_line(FILE *file, char *buffer) {
/*similar to fgets except that it can read a line of text of unbounded size*/
FILE *fp = file;
int c, i = 0 ;
/*read from file ptr until newline or EOF is reached*/
while ((c = getc(fp)) != EOF) {
buffer[i++] = c;
}
if (c == '\n') {
buffer[i++] = c;
}
buffer[i] = '\0';
}
FILE *safe_open (char *file_name, char *mode)
{
FILE *fp;
if ((fp = fopen (file_name, mode)) == NULL)
{
fprintf (stdout, "Could not open file: %s\n", file_name);
exit (EXIT_FAILURE);
}
return fp;
}
output:
Code:
./simple_test file1.txt file2.txt
Hello This is a test to see if the get line funstion works.
T_߿�_߿h��.N=�{߿�G�8_߿���
file2 is not used, io is through printf