user1
user1

Reputation: 59

Writing user input to a file in C programming

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 I haven't been successful. Here's what I have so far.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main ()
{
    FILE *fileptr;
    char id [30];
    char name [47];
    char amt[50];

    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;
}

Upvotes: 1

Views: 25468

Answers (2)

Stanley
Stanley

Reputation: 4486

Use:

fscanf(stdin, "%s", name);

But better still, use scanf instead, as kol mentioned. This is because scanf() is designed to read the user response from the screen while fscanf() is for scanning from any input streams (which are usually files).

And the statement should be reading from the screen (stdin), not from the file (which was opened as "write" only).

Upvotes: 2

kol
kol

Reputation: 28728

Use scanf to read user input, and fprintf to write it to the file. Then use fscanf to read from the file, and printf to display what you have read. See cplusplus.com for the details and sample code.

EDIT:

Here is an example (please run the executable from the command line):

#include <stdio.h>
#include <string.h>

int main()
{
  FILE *file;
  int i;
  char firstName[32];
  char lastName[32];
  int found = 0;

  // Open the file for writing
  file = fopen("records.txt", "wt");
  if (!file)
  {
    printf("File could not be opened\n\a\a");
    getchar();
    return -1;
  }

  // Read and save data
  for (i = 0; i < 3; ++i)
  {
    // Read data
    printf("Record #%d\n", i + 1);
    printf("Enter first name: "); scanf("%s", firstName);
    printf("Enter last name:  "); scanf("%s", lastName);
    printf("\n");

    // Save data
    fprintf(file, "%s\t%s\n", firstName, lastName);
  }

  // Close the file
  fclose(file);

  // Open the file for reading
  file = fopen("records.txt", "rt");
  if (!file)
  {
    printf("File could not be opened\n\a\a");
    return -1;
  }

  // Load and display data
  i = 0;
  while(!feof(file) && !found)
  {
    ++i;
    fscanf(file, "%s\t%s", firstName, lastName);
    if (strcmp(firstName, "John") == 0 && strcmp(lastName, "Doe") == 0)
    {
      printf("Record found (#%d): %s %s\n", i, firstName, lastName);
      found = 1;
    }
  }
  if (!found)
    printf("Record could not be found");

  // Close the file
  fclose(file);

  return 0;
}

Upvotes: 0

Related Questions