Writing and reading CSV file in C wierd output - c

I'm new to C language and I'm trying to save data to a .csv and read the same data in a very simple program.
char c;
FILE *fp;
fp = fopen("file.csv", "w+");
fprintf(fp, "Hello;World\nLine");
fclose(fp);
fp = fopen("file.csv", "r");
while (getc(fp) != EOF) {
printf("%c", getc(fp));
}
fclose(fp);
I don't know why the output is wrong:
el;ol
ie
Thanks in advance

Because you are reading a character in the loop condition (so it prints out every other one when printing), and reading another one when printing it out. Try this:
int ch;
while ((ch=getc(fp)) != EOF) {
printf("%c", ch);
}

Here:
while (getc(fp) != EOF) {
printf("%c", getc(fp));
}
You are calling getc() twice every time through the loop, but only printing one character. So you get half te hrces rm te fl n ls h ohr hl.

Related

why fgetc() doesn't work well in my program (c language)?

1, 2, 3 // a.txt
This program is for opening the file, counting the numbers and reading the first letter of txt file.
When I tried debugging, digit_char = fgetc(fp); doesn't worked properly. digit_char was empty. I used dynamic allocation to save the numbers in the array. There was no warning but the answer was not what I wanted. (digit_char=1)
FILE* fp;
char digit_char;
int NUM=1;
fp = fopen("a.txt", "r");
char ch;
do
{
ch = fgetc(fp);
if (ch == ',')
{
NUM++;
}
} while (ch != EOF);
int* arr;
arr = (int*)malloc(sizeof(int) * NUM);
digit_char = fgetc(fp); // error...?
free(arr);
fclose(fp);
======
The following code fgetc() works very well. 1is saved in digit_char
FILE* fp;
char digit_char;
int NUM=3;
fp = fopen("a.txt", "r");
int arr[3];
digit_char = fgetc(fp);
//free(arr);
fclose(fp);
return 0;
I don't know why the first program doesn't work well..
Once you have reached EOF, you're really at the end of the file. There's nothing more to read.
You need to rewind to the beginning of the file before attempting to read again.
Or at least seek to an earlier position.
Note that it's not possible to rewind or seek in the standard input stream stdin. To continue reading from stdin even after the user pressed the "end-of-file" button sequence, you need to clear the "error".

In C, "getc" reads only three lines from text file

My Code is HERE
int main(){
FILE *fp;
fp = fopen("dic.txt", "r");
while(getc(fp) != EOF){
if(getc(fp) == ' '){
printf("up ");
}
}
}
My dic.txt is HERE
dic.txt
my predict is that "up up up up "
because, there are four space " "
but it printed "up " only one
what is problem?
You are calling getc twice per iteration of the loop; one of these two calls compares the character to EOF, while the other call compares the character to ' '.
This has two consequences:
Your program will only print "up" for the spaces which are on even position, and will miss all spaces which are on odd position;
Your program might make one extra call to getc after reaching EOF the first time.
How to fix
You need to make a single call to getc per iteration of the loop. Save the character returned by getc to a local variable; then use this variable to check for spaces in the body of the loop, and to check for EOF in the condition of the loop.
You want this:
#include <stdio.h>
int main() {
FILE* fp;
fp = fopen("dic.txt", "r");
if (fp == NULL)
{
printf("Can't open file\n");
return 1;
}
int ch; // int is needed her, not char !!
while ((ch = getc(fp)) != EOF) { // read one char and check if it's EOF in one go
if (ch == ' ') {
printf("up ");
}
}
}
You need to call getc once only in the loop, otherwise you skip one out of two characters.
Bonus: you need to check if fopen fails.
Try Out This Code:
FILE *fp;
fp = fopen("dic.txt", "r");
int ch = getc(fp);
while(ch != EOF){
if(getc(fp) == ' '){
printf("up ");
}
}
return 0;

Complete equations from a text file in C

I need to write some code to read an equation from a text file and write the answer to a new one, and I'm completely stuck
I've managed to read the question and print it in terminal as characters, but that's it.
this new code can't even do that.
for those asking, the exact wording of the question is this:
"Read an input file: questions.txt; and produce a program that creates an output file answers.txt that includes
the question and the answer for each line in the questions file.
For example, if the line in questions is:
5*5
the answer file should read:
5*5 = 25
Allow for the following operations: +, -, *, /, % and for the correct order of operations. Also allow for at least 2
operators (3 operands), for example:
3+5*5 = 28"
My main problem is reading the equation from the text file and separating it into numbers and the operator symbol
FILE *fp;
int a, b, c, ch, i, number[100];
char input[5];
fp = fopen ("questions.txt", "r");
while(1)
{
ch = fgetc(fp);
if (ch == EOF)
{
break;
}
else
{
input[i] = ch;
}
}
fclose(fp);
printf("%s", input);
}
There are errors:
check file has been open correcly: if (fp != NULL)
i = 0; on begin, now we dont know value
input[i] = ch; => input[i++] = (char)ch;
if (ch == EOF) => if (ch == EOF && i < 4) 4 because 5 - 1 and move this to const or macro
After break of while input[i] = '\0';
You need to open the file you want to read from in read mode with the normal fopen('questions.txt', 'r') like you did. Next, you need to fopen('newFile.txt', 'w') you want to write to in w write mode. Use a while loop to get each character of the questions.txt file with getc(fileToRead) while you haven''t hit the end of the questions.txt file, hence ... != EOF, and write to the newFile.txt. The printf("%c", c) is to print each character as you read it from questions.txt.
FILE *fileToRead, *fileToWrite;
int c;
//open the questions.txt file in read mode
*fileToRead = fopen ("questions.txt", "r");
//create newFile.txt and open it in write mode
*fileToWrite = fopen ("newFile.txt", "w");
while ((c = getc(fileToRead)) != EOF) {
putc((char)c, fileToWrite );
printf("%c", (char)c);
}
fclose(fileToRead);
fclose(fileToWrite);

fscanf() wont read data after done counting lines C

first of all thanks to Stack Overflow, I have a problem in my C Code in reading files using fscanf().
FILE *edit = fopen("test.txt", "r");
int id_temp;
fscanf(edit, "%d", &id_temp);
printf("%d\n", id_temp);
fclose(edit);
system("pause");
I can read it in this way but when I add on counting lines,
FILE *edit = fopen("test.txt", "w");
char ch;
int count = 0;
do
{
ch = fgetc(edit);
if (ch == '\n') count++;
} while (ch != EOF);
printf("Total number of lines %d\n", count);
int id_temp = 0;
fscanf(edit, "%d", &id_temp);
printf("%d\n", id_temp);
fclose(edit);
system("pause");
The id_temp will print 0 instead of read the number from the file itself. While on the first scenario, it prints me 2 (correct).
Thank you for your time, Any idea guys?

C Programming - Copy File Buffer and Write to File

I'm making some small changes to a preexisting application. The app is writing lines of text to a buffer and then flushing the buffer. I'm not sure when it actually writes the text to the file, but I'm trying to copy everything in that buffer and write a copy of it all out to a completely different file.
Below is the last line of writing to the preexisting buffer before it eventually calls fflush().
fprintf(_log, "-- FINAL TEXT LINE --\n");
Below is my code that I'm using in an attempt to copy that buffer to a separate file which is dynamically named according to the log time. This custom-%ld.log does not already exist and needs to be created.
char tmp[sizeof(_log)];
sprintf(tmp, "custom-%ld.log", (long int)lf->time);
FILE *fp1, *fp2;
char a;
fp1 = _log;
fp2 = fopen(tmp, "a");
if (fp2 != NULL) {
do {
a = fgetc(fp1);
fputc(a, fp2);
} while (a != EOF);
fflush(fp1);
fclose(fp2);
}
fflush(_log);
I'm sure my mistakes are very basic, but I don't know what I'm doing. I've tried dozens of suggestions on other websites, and suggestions here from other questions, but I'm not having any luck.
Yes, there are a few mistakes in here.
This will allocate a buffer of 4 or 8 bytes depending on the word size of your computer. 'sizeof' is a compile time directive that gives you the size of the underlying type.
char tmp[sizeof(_log)];
So do this instead (where 100 is just a big enough number to hold the result):
char tmp[100];
Next using a char for 'a' will not be able to hold the EOF value. Use int.
int a;
By fixing the definition of 'a' your loop is now not infinite, but it will eventually write the constant EOF to the file, which will be some garbled character. Change it like so:
while ((a = fgetc(fp1)) != EOF) {
fputc(a, fp2);
}
So in the end you should have:
char tmp[100];
sprintf(tmp, "custom-%ld.log", (long int)lf->time);
FILE *fp1, *fp2;
int a;
fp1 = _log;
fp2 = fopen(tmp, "a");
if (fp2 != NULL) {
while ((a = fgetc(fp1)) != EOF) {
fputc(a, fp2);
}
fflush(fp1);
fclose(fp2);
}
fflush(_log);
You are writing EOF to file before checking it with
do {
a = fgetc(fp1);
fputc(a, fp2);
} while (a != EOF);
You could try
int a; // make sure you have the correct type
while((a = fgetc(fp1)) != EOF)
fputc(a, fp2);
}
EOF is not (except some legacy formats) part of the file. It is an indicator returned by file reading functions.
Note that fflush(fp1); is undefined behaviour when fp1 is opened for input.
You say "custom-%ld.log" does not already exist yet you open it with
fp2 = fopen(tmp, "a");
Which would append, if you forgot to delete a previous version. To make sure it is a new file, open with
fp2 = fopen(tmp, "w");

Resources