Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

-Write a function which reads a line of any length from a file, and returns it a

ID: 3858418 • Letter: #

Question

-Write a function which reads a line of any length from a file, and returns it as a string.

-You are not permitted to use fgets.

-Write a test program to confirm that your function is correct.

So far I have this but cant get seem to send the file name through to the function "readin"

Thanks for your help!

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#define kFileLocation "/Read File/Read File/Data"

char* readin(FILE* file) {

  

int size = 100;

char* result = malloc(sizeof(char)*size);

int position = 0;

int next;

int count = 0;

  

while(1) {

next = fgetc(file);

if (next == EOF || next == ' ') {

result[position] = ' ';

return result;

}

if (count == 99) {

size = size + size;

result = realloc(result , size);

count = 0;

} else {

result[position++] = (char)next;

count++;

}

}

}

int main (int argc, char*argv[]) {

  

char* outputFile;

FILE* DataFile;

  

outputFile = readin(kFileLocation);

  

printf("%s ",outputFile);

return 0;

}

Explanation / Answer

Problems in your code

1) You were not opening the file to read. You were just sending the filename to the function. So open it first and then send the file pointer to the function. Look at the code below.

int main (int argc, char*argv[]) {
  
char* outputFile;
FILE *DataFile;

DataFile = fopen(kFileLocation, "r");

outputFile = readin(DataFile);

2) Please supply the file name with the full path along with the extension. Else if you want to use only the file name then the file must be in the working directory/folder of the C program. e.g., look at the code below.

#define kFileLocation "C:/Users/Anjan/Desktop/Data.txt"