How to store two lines in a text file into two strings - c

I'm trying to read a text file that will contain two lines, something like this:
18,3,4,c;19,3,5,D
19100,18,18;19102,3,2
and i want to store the first line in a string called Students and the second one into another string called Courses.
I have wrote this code but it stores one line only and i can't get it to work with the second line
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fscanf(fptr, "%[^\n]", Students);
fclose(fptr);
Can anyone help me with that? I'm a newbie to c and i can't get how to do so, Thank you in advance.

FILE *fptr;
char buffer[255] = {'\0'};
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fgets(Students, sizeof(Students), fptr);
fgets(Courses, sizeof(Courses), fptr);
fclose(fptr);
This line fgets(Students, sizeof(Students), fptr); will start reading from the begginning of the file and store the first line to Students char array & then fgets(Courses, sizeof(Courses), fptr); will read the second line and store it into Courses char array.
Make sure that the size of Students & Courses is large enough to accommodate each line into them.

You may try fscanf() for the problem:
#include <stdio.h>
int main(void) {
char Students[100], Courses[100];
FILE *fp = fopen("program.txt", "r");
if (!fp) {
printf("File wasn't opened.\n");
return -1;
}
fscanf(fp, "%s \n", Students);
fscanf(fp, "%s", Courses);
printf("%s\n", Students);
printf("%s\n", Courses);
fclose(fp);
return 0;
}
My program.txt contains:
John_Doe
Mathematics
Sample Output
John_Doe // Students
Mathematics // Courses

Use something like:
fscanf(fptr, "%[^\n]\n%[^\n]]\n", Students,Courses);
Where you tell scanf() to read up to a new-line, read and discard the new line, then do it again.

Related

Why is the file storing binary characters? getw() and putw() were asked to be used in the question

I've used a ".txt" extension while reading and writing the file, also the file mode is corresponding to that of "text" type of file. The program runs fine, but instead of storing an ASCII character in the file, it is storing binary characters. I need some assistance here. Thank you.
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
scanf("%d", &n1);
fp = fopen("hello.txt", "w");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
fprintf(fp, "%d", n1);
//fclose(fp);
//rewind(fp);
fp = fopen("hello.txt", "r");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
//n2 = getw(fp);
fscanf(fp, "%d", n1);
printf("%d", n1);
fclose(fp);
}
If you are going to close and reopen the file you don't need rewind. Or you can open the file to read and write, and then you can use rewind. Both work, here is a sample of the latter:
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
if (scanf("%d", &n1) == 1) // checking if the input was correctly parsed
{
fp = fopen("hello.txt", "w+"); // open to read and write
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
putw(n1, fp); // write to the file
rewind(fp); // go back to the beginning of the file
n2 = getw(fp); // get the data
printf("%d", n2);
fclose(fp);
}
else
{
puts("Bad input");
}
}
Live sample
There is still the matter of possible integer overflow when reading from stdin, if there is no requirement to guard against that, make sure to at least document the vulnerability, otherwise the advice is to use fgets to read input and strtol to convert the value.
You should send address of a variable in fscanf, like this:
fscanf(fp,"%d",&n1);

How to allow other sentences to be in a file?

In this code whenever I write a new sentence, it replaces the previous sentence in a file that I put earlier. I want to not replace the previous sentence and also allow other sentences in that file line after line.
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
// creating file pointer to work with files
FILE *fptr;
// opening file in writing mode
fptr = fopen("file.txt", "w");
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
Open the file in append mode.
fptr = fopen("file.txt", "a");
https://en.cppreference.com/w/c/io/fopen

C - Read file line by line

The code is running well, it's just that I feel there are still many mistakes and give me a little direction to improve in the future. I want to learn how to maintain the code properly.
fix the code as it should!
Data.txt
[1] Line numbers 1.
[2] Line numbers 2.
[3] Line numbers 3.
[4] Line numbers 4.
[5] Line numbers 5.
[6] Line numbers 6.
My code:
#include <stdio.h>
#include <stdlib.h>
int getLengthFile(char *namafile)
{
FILE *fptr;
int n =0;
fptr = fopen(namafile, "r");
if(fptr != NULL){
char c;
while((c = getc(fptr)) != EOF) {
++n;
}
fclose(fptr);
}
return n;
}
int main(){
FILE *fptr;
int i;
fptr = fopen("Data.txt","r");
if(fptr != NULL){
printf("Succes reads file!\n");
if(getLengthFile("Data.txt")>0){
char strLine[225];
while(fgets(strLine,225,fptr) != NULL){
printf("%s",strLine);
}
}else{
printf("File is empty!\n");
}
fclose(fptr);
}else{
printf("Error reads file!\n");
}
return 0;
}
Here is a more or less fixed version of the code presented in the first edition of the question, where the getLengthFile() function was not present. In my opinion, that function does not provide useful functionality. If you must report that the file contained no data, you could do so by counting the number of times fgets() returns any data — if it returns any data, the file was not empty.
#include <stdio.h>
int main(void)
{
const char filename[] = "Data.txt";
FILE *fptr = fopen(filename, "r");
if (fptr == NULL)
{
fprintf(stderr, "Error opening file %s for reading!\n", filename);
return 1;
}
printf("Success opening file %s for reading\n", filename);
char strLine[225];
while (fgets(strLine, sizeof(strLine), fptr) != NULL)
printf("%s", strLine);
fclose(fptr);
return 0;
}
When there is no file Data.txt, example output is:
Error opening file Data.txt for reading!
When there's a file containing one short line of data, example output is:
Success opening file Data.txt for reading
data from the file Data.txt
I also tested it on a file with longer lines, including lines with as many as 380 characters, and the output from the program was the same as the input except for the line saying 'Success opening file Data.txt for reading'.

Copy from one txt file to another with c

I am having problems with copying txt files. I need to info from one file to another.
My code looks like this,
_tprintf (TEXT("%s\n"), FindFileData.cFileName);
memset(fileName, 0x00, sizeof(fileName));
_stprintf(fileName, TEXT("%s\\%s"), path, FindFileData.cFileName); //iegust
FILE *fptr = fopen(fileName, "r");//atver
fscanf(fptr,"%[^\n]",c); //iegust datus no faila
printf("Data from file:\n%s",a);
strcpy(a, c); //nokope datus
buffer2 = strtok (c, ","); //norada partraukumu un tadas lietas
while (buffer2) {
buffer2 = strtok (NULL, ",");
if(i<1){ printf("%s\n", c);}
i++;
while (buffer2 && *buffer2 == '\040'){
buffer2++;
// TODO ieliec iekavinas
}
}
And after that I use basic fputs().
My problem is that this code ignores new lines. It prints out fine, each string in it's own line, but that does not happen in file. (\n).
Your problem is that you just need to copy information from one file to another. So, why you don't use a simple solution to do it than your. I have a snipet code can solve your problem easily as shown below.
If I am wrong about your question, please give me advices.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}

Adding Multiple Lines to a Text File Output?

I am using a basic C code to print to a text file:
FILE *file;
file = fopen("zach.txt", "a+"); //add text to file if exists, create file if file does not exist
fprintf(file, "%s", "This is just an example :)\n"); //writes to file
fclose(file); //close file after writing
printf("File has been written. Please review. \n");
My question is regarding the above code: I have multiple lines I have printed that I would like to be saved to the text document. How can I easily include multiple lines of code to be printed in my file using the above code?
Move file writing into a procedure:
void write_lines (FILE *fp) {
fprintf (file, "%s\n", "Line 1");
fprintf (file, "%s %d\n", "Line", 2);
fprintf (file, "Multiple\nlines\n%s", "in one call\n");
}
int main () {
FILE *file = fopen ("zach.txt", "a+");
assert (file != NULL); // Basic error checking
write_lines (file);
fclose (file);
printf ("File has been written. Please review. \n");
return 0;
}
There are lots of ways to do this, here's one:
#include<stdio.h>
#include<string.h>
int appendToFile(char *text, char *fileName) {
FILE *file;
//no need to continue if the file can't be opened.
if( ! (file = fopen(fileName, "a+"))) return 0;
fprintf(file, "%s", text);
fclose(file);
//returning 1 rather than 0 makes the if statement in
//main make more sense.
return 1;
}
int main() {
char someText[256];
//could use snprintf for formatted output, but we don't
//really need that here. Note that strncpy is used first
//and strncat used for the rest of the lines. This part
//could just be one big string constant or it could be
//abstracted to yet another function if you wanted.
strncpy(someText, "Here is some text!\n", 256);
strncat(someText, "It is on multiple lines.\n", 256);
strncat(someText, "Hooray!\n", 256);
if(appendToFile(someText, "zach.txt")) {
printf("Text file ./zach.txt has been written to.");
} else {
printf("Could not write to ./zach.txt.");
}
return 0;
}
notice the strncpy and strncat functions since you aren't really utilizing the formatted input that comes with the xprintf functions.

Resources