I want to read each element of my text file which includes new lines and also spaces. Here is my code
void test3()
{
char a;
FILE *csv;
csv=fopen64("C:\\Users\\Md. Akash\\Desktop\\csv\\Book1.csv","r");
int i;
for(i=0;;i++)
{
if(fgetc(csv)==EOF)
break;
a=fgetc(csv);
printf("%c",a);
}
}
This code skips one character.
You're calling fgetc twice in every iteration of the for loop. And you are not printing what you get the first time.
Change:
if(fgetc(csv)==EOF)
break;
a=fgetc(csv);
printf("%c",a);
to:
if((a = fgetc(csv))==EOF)
break;
printf("%c",a);
Note: fgetc returns an int. So a should be defined as an int.
Try replacing for loop by the following:
/*
Note:
a = fgetc(csv) returns a character from the file pointed to by **csv** o returns **EOF** if the End Of File is reached.
Therefore, it is probably a good idea to read every character from the file until the EOF is reached.
The following **while** loop demonstrate just that.
*/
while((a =fgetc(csv)) != EOF){
printf("%c", a)
}
Related
I'm making somewhat like an othello game. I receive a file that contains strings, and i have to read and process them, making the board as it goes.
Example of the file received:
Alejandro,B
Federico,N
B
D6
C4
G5
then i would convert the characters to numbers, so it can fit in the int board[8][8] i use
I was expecting that when it reaches the EOF it would get out of the loop, but instead it never stops the loop and keeps reapeting the last line with the printf.
This is in the main function:
while( EOF != 1 && *error != 1)
{
tomaJugada(&fp,jugada); //takes 1 line of the file
toupper(jugada[0]);
int columna = convierte_a_int(jugada[0])-1; //converts the letter to a number
int fila = (jugada[1]-'0')-1; //converts the char number to int number
printf("columna %i, fila %i \n",columna, fila);
}
This is the auxiliary function:
void tomaJugada(FILE** fp, char jugada[])
{
fgets(jugada,5,*fp);
jugada[2] = '\0';
//jugada[strcspn(jugada, "\n")] = 0;
}
I have seen people using thi:
int ch = getc(fp);
while (ch != EOF){...
but it would consumme data that i need to use, maybe i'm using it wrong?
Resumming: i want to use all the data in the file, reach de EOF, and end the loop. How can i put the condition for the EOF?
I hope i explained myself well, i appreciate any help
EOF in c is just a constant (typically -1), EOF != 1 would always evaluate to the same (that is guaranteed to be true as EOF will always be negative). What you need to do is to check if fgets returns null pointer (that is in the tomaJugada function) and when that happens, then either an error occurred or you've reached the end of the file. To disambiguate between the two you could use the feof function for instance.
#include<stdio.h>
int main()
{
char name[20];
FILE *fptr=fopen("Student1.txt","w");
fputc('J',fptr);
fclose(fptr);
FILE *ptr=fopen("Student1.txt","r");
char ch;
// ch=fgetc(ptr);
fscanf(ptr,"%c",&ch);
while(ch!=EOF)
{
printf("%c",ch);
fscanf(ptr,"%c",&ch);
}
printf("\n");
fclose(ptr);
return 0;
}
I have been getting an infinite loop when I run this code.
I'm stuck at this code for so long now.
Please try to help.
An infinite loop typically means that the loop condition ch != EOF remains true forever. The only way you set ch is via the two calls to fscanf(ptr,"%c",&ch);. fscanf() returns EOF when the end of a file is reached which is different than setting the (out) argument ch. Here is how I would write it:
#include <stdio.h>
int main() {
FILE *fptr=fopen("Student1.txt","w");
if(!fptr) {
printf("fopen failed\n");
return 1;
}
fputc('J',fptr);
fclose(fptr);
FILE *ptr=fopen("Student1.txt","r");
if(!ptr) {
printf("fopen failed\n");
return 1;
}
for(;;) {
char ch;
int r = fscanf(ptr,"%c",&ch);
if(r == EOF)
break;
if(r != 1) {
printf("fscanf failed\n");
return 1;
}
printf("%c",ch);
}
printf("\n");
fclose(ptr);
return 0;
}
Consider refactoring the two fopen() calls into a single FILE * fptr = fopen(..., "rw") then truncate the file with ftruncate(fileno(fptr), 0).
The problem is that fgetch() and fscanf() have different interfaces.
fgetch() returns an int value to designate all the possible character values (from 0 to 255) and also EOF (which is none of them, generally implemented as -1). fgetch() returns EOF to indicate the end of file condition (which is not a character, but merely a situation)
fscanf() stores a representation of the char just read in the variable pointed to. But it will never store EOF in the variable (indeed, it will store nothing at all, in the case of an end of file condition), as EOF doesn't represent a character, it is not worth storing it in a char variable.
fscanf() returns the number of format specifiers that it could satisfy, so in this case
// ch=fgetc(ptr);
fscanf(ptr,"%c",&ch);
while(ch!=EOF)
{
printf("%c",ch);
fscanf(ptr,"%c",&ch);
}
that will never happen (It will, in case you enter a char value that could be converted as a signed integer into the value EOF has, just try to enter the character value 0xff (in case you can do that from the keyboard). But that is completely incorrect, as the character stored in the variable would be a true character (that happens to convert to -1 when converted to an int) and it can happen in the middle of a file. The infinite loop happens because on an end of file, nothing is stored on the char variable, and so ch never changes again, if it was not the magic character described above, it will never satisfy the condition to get out of the loop.
The actual behaviour of fscanf() is that it will return 1 for all the characters actually read, and 0, on satisfying the end of file condition. A good working example would be:
while (fscanf(ptr, "%c", &ch) == 1) {
printf("%c",ch);
fscanf(ptr,"%c",&ch);
}
I Couldn't understand this code i've left comment line about strcopy. Can you explain it to me? Thanks already. I'm new at c and trying to improve myself. Sometimes i stuck at somewhere and in this situation i couldn't find any solution.
#include <stdio.h>
#include <string.h>
#define SIZE 1000
int main(){
int lwd,cnt;
char read1[SIZE];
char true;
FILE *r = fopen("test.txt","r");
if(r==NULL){
printf("Er.");
}
FILE *cpy =fopen("temp","w");
if(cpy==NULL){
printf("Er.");
fclose(r);
}
printf("Please enter whic line you wanna remove:");
scanf("%d",&lwd);
while(!feof(r)){
strcpy(read1,"\0"); // what does it mean?
fgets(read1,SIZE,r);
if(!feof(r)){
cnt++;
if(cnt != lwd){
fprintf(cpy,"%s",read1);
}
}
}
fclose(r);
fclose(cpy);
remove("test.txt");
rename("temp","test.txt");
FILE *read;
read = fopen("test.txt","r");
if(read == NULL){
printf("Error.");
fclose(read);
}
true=fgetc(read);
while(true != EOF){
printf("%c",true);
true=fgetc(read);
}
getch();
return 0;
}
The statement
strcpy(read1,"\0");
is just copying an empty string to initialize read1.
It's a silly way to do it; read1[0] = 0; is just as good, but as #chux points out in the comments, initializing read1 isn't necessary, and there are other things wrong with the code (e.g., checking result of fgets).
You can see the documentation for the strcpy below.
https://i.stack.imgur.com/AN38r.png
You can see the strcpy copies the second string argument in the first string argument. The first argument is the destination where the string is copied. The second argument is the source from which the complete string is copied.
Therefore we can say that the strcpy line is just to ensure that read1 is always empty before the reading the next line.
If we skip this line then a case where the length of the previously read line is more than the current line can give errors.
It is almost a redundant step here as fgets replaces the '\n' with '\0'. Thus, characters after that do not matter.
I need to save every line of text file in c in a variable.
Here's my code
int main()
{
char firstname[100];
char lastname[100];
char string_0[256];
char string[256] = "Vanilla Twilight";
char string2[256];
FILE *file;
file = fopen("record.txt","r");
while(fgets(string_0,256,file) != NULL)
{
fgets(string2, 256, file);
printf("%s\n", string2);
if(strcmp(string, string2)==0)
printf("A match has been found");
}
fclose(file);
return 0;
}
Some lines are stored in the variable and printed on the cmd but some are skipped.
What should I do? When I tried sscanf(), all lines were complete but only the first word of each line is printed. I also tried ffscanf() but isn't working too. In fgets(), words per line are complete, but as I've said, some lines are skipped (even the first line).
I'm just a beginner in programming, so I really need help. :(
You're skipping over the check every odd number of lines, as you have two successive fgets() calls and only one strcmp(). Reduce your code to
while(fgets(string_0,256,file) != NULL)
{
if( ! strcmp(string_0, string2) )
printf("A match has been found\n");
}
FWIW, fgets() reads and stores the trailing newline, which can cause problem is string comparison, you need to take care of that, too.
As a note, you should always check the return value of fopen() for success before using the returned pointer.
I am just trying to read each character of the file and print it out but when the file finishes reading, but I am getting a bunch of ? after it finishes reading. How do I fix it?
#include <stdio.h>
int main(void){
FILE *fr; /* declare the file pointer */
fr = fopen ("some.txt", "r"); /* open the file for reading */
/* elapsed.dta is the name of the file */
/* "rt" means open the file for reading text */
char c;
while((c = getc(fr)) != NULL)
{
printf("%c", c);
}
fclose(fr); /* close the file prior to exiting the routine */
/*of main*/
return 0;
}
In spite of its name, getc returns an int, not a char, so that it can represent all of the possible char values and, in addition, EOF (end of file). If getc returned a char, there would be no way to indicate the end of file without using one of the values that could possibly be in the file.
So, to fix your code, you must first change the declaration char c; to int c; so that it can hold the EOF marker when it is returned. Then, you must also change the while loop condition to check for EOF instead of NULL.
You could also call feof(fr) to test end of file separately from reading the character. If you did that, you could leave c as a char, but you would have to call feof() after you read the character but before you printed it out, and use a break to get out of the loop.
If unsuccessful, fgetc() returns EOF.
int c;
while ((c = getc(fr)) != EOF)
{
printf("%c", c);
}
Change this
char c;
while((c = getc(fr)) != NULL)
{
printf("%c", c);
}
to
char c;
int charAsInt;
while((charAsInt = getc(fr)) != EOF)
{
c = (char) charAsInt;
printf("%c", c);
}
In other words: You need to compare against EOF, not NULL. You also need to use an int variable to receive the return value from fgetc. If you use a char, the comparison with EOF may fail, and you'll be back where you started.
fgetc() returns EOF on end-of-file, not NULL.
Replace "NULL" with "EOF".
Others have already addressed the issue you're having, but rather than using printf("%c", c); it is probably much more efficient to use putchar(c);. There is quite a bit of overhead involved when you ask printf to print just one character.
getc returns an int.
change char c, to int c.
also getc returns EOF,
change your test against NULL to a test against EOF