-2

I am working on a program to write user input to a file and then search for a specific record in the file and output it to the screen. I tried using fgets and also fputs but havent been successful

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
  {
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
int i;

fileptr=fopen("C:\\Users\\Andrea\\Documents\\Tester.txt","w");
 if (fileptr == NULL) {
     printf("File couldn't be opened\n\a\a");
     fclose(fileptr);
     exit(0);
  }

  printf("Enter name: \n");
  fscanf(fileptr,"%c",name);
  fputs(name,fileptr);
  fclose(fileptr);
  printf("File write was successful\n"); 
  return 0;
  }
7
  • 3
    Something seems to have gone wrong during posting. Please click edit to post your program (and perhaps describe what's "not working so well"). Commented Nov 13, 2011 at 22:23
  • 1
    Can you show us the code that you have tried? Commented Nov 13, 2011 at 22:23
  • There is no code attached. Please improve your message. Commented Nov 13, 2011 at 22:30
  • sorry for the mistake.... i have added the code Commented Nov 14, 2011 at 0:07
  • why are you trying to close fileptr if it is null? Commented Nov 14, 2011 at 0:17

1 Answer 1

0

There are several problems.

  1. You are trying to read from fileptr.
  2. You are reading only one character, but treat the name array as if it was read in correctly.

A start would be:

  [...]
  printf("Enter name: \n");
  if (fgets(name, sizeof name, stdin)) {
    fputs(name,fileptr);
    fclose(fileptr);
    printf("File write was successful\n");
  } else {
    printf("Read error.\n");
  }

But that's not all: you have forgotten to put error checking. E.g., how do you know that your "File write was successful\n" if you don't check at least the return value of fputs()?

Sign up to request clarification or add additional context in comments.

2 Comments

this needs to be done to get 10 records, could a for loop work?
1. No, that could not work. Why do you want to read from fileptr which you have opened for "w"riting? I think you wanted to read from stdin? 2. A for loop would indeed work. But befor we are putting together fragments, you might want to define exactly what you try to achieve, so we can help "as a block".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.