fscanf() wont read data after done counting lines C - 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?

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".

Would it be possible to create a function that reads half a text file in C?

(I'm very new to C btw but I've looked before coming here, and I've only seen questions about finding specific strings in text files)
void *readFile() {
FILE* myFile;
myFile = fopen ("SampleFile.txt","r");
char line[150];
while(!feof(myFile)) {
fgets(line, 150, myFile);
puts(line);
}
fclose(myFile);
return NULL;
}
I know this reads and prints the whole file but is there a way I could get just the first or second half of the file to be read?
First you will have to know the size of total line in the file. You can do this by adding and count and then increment it after every line. After this, adjust your loop condition to for(int i=0; i < count; i++). For this loop condition you can read and print all line but if you adjust this condition to for(int i=0; i < count/2; i++) this will print first half and for(int i=count/2; i < count; i++) this will print 2nd half.
Would it be possible to create a function that reads half a text file ... ?
To read half the file, read a byte - skip a byte.
int ch;
while((ch = fgetc(myFile)) != EOF) {
putchar(ch);
fseek(myFile, 1, SEEK_CUR);
}
To print every other line, use the return value of fgets() and toggle a flag print.
bool print = true;
while(fgets(line, sizeof line, myFile)) {
if (print) {
fputs(line, stdout);
}
print = !print;
}
... is there a way I could get just the first or second half of the file to be read?
Awww, that does not look like much fun to add that condition at the end of the the post.
First find file length:
How can I get a file's size
How do you determine the size of a file
On Linux, I would use stat64();
long size = foo(); // from one of above 3 ideas
To read the first half:
rewind(myFile);
int ch;
while(size-- > 0 && (ch = fgetc(myFile)) != EOF) {
putchar(ch);
}
To read the 2nd half:
fseek(myFile, size/2, SEEK_SET);
int ch;
while((ch = fgetc(myFile)) != EOF) {
putchar(ch);
}
Heres is a fun idea to print the first half, just write a few queue functions.
queue *q = q_init();
int ch;
// Read 2 bytes, save, write earliest byte
while((ch = fgetc(myFile)) != EOF) {
q_append(q, ch);
ch = fgetc(myFile);
if (ch != EOF) q_append(q, ch);
ch = q_get(q);
putchar(ch);
}
q = q_uninit(q);
If you truely don´t want to read the other half of the file there is no way to do that unless you know the size of the file. Other answers suggest that you get the size by reading all the file and counting the number of lines, which is fine if you can do that, as it is with a small file.
If you have a file of billions of lines you don’t want to do that. In this case the only option is to use some operating system function to get the size of the file. But this will usually only give you the size of the file, not the number of lines, so you wouldn’t really know where to stop/start.

Opening File byte by byte printing in hex

C programmer newcomer here.
I'm trying to open a .obj file (containing LC3 instructions) and print them in groups of 2 bytes line by line in hex. I've tried opening the file and iterating through char by char and printing in hex but I am unsure how to group the bytes together in groups of 2 to print them together. I am also printing out a group of "fffffff"s for the bytes that lead with a 1 (I assume).
void readFile(const char *fileName) {
FILE *file;
file = fopen(fileName, "rb");
char ch;
while ((ch = fgetc(file)) != EOF) {
if (isprint(ch)) {
printf("%x", ch);
}
else {
printf("%02x", ch);
if (ch == '\n') {
fputs("\n", stdout);
}
}
}
fclose(file);
}
The output I am looking to achieve is:
0x4500
0x2009
0xe209
0xa409
But I am getting:
0x45
0020
09fffffffe209fffffffa40956
I understand that the hex is printing the excess "ffffffff"s due to not being an unsigned char but I am struggling to print close to the desired output. Any help in printing in 2 byte groups or how to remove the "fffffff"s would be greatly appreciated, and I'm really struggling.
The getchar()
family of functions (including getc() and fgetc()) all behave similarly; they return an int, not a char. Read the values into an int and live life happy.
void readFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (file == 0)
return;
int ch;
while ((ch = fgetc(file)) != EOF)
{
printf("0x%.2x", ch);
if ((ch = fgetc(file)) == EOF)
break;
printf("%.2x\n", ch);
}
putchar('\n');
fclose(file);
}
If there's an even number of bytes in the file, you'll get an extra newline at the end. If that's a problem, keep a record of whether you exit the loop at the top (no newline needed) or from the middle (newline needed).
Both isprint(ch) and ch == '\n' have absolutely nothing to do with 2-byte grouping.
Perhaps you want something simple like this:
unsigned char ch;
while ((ch = (unsigned char)fgetc(file)) != EOF) {
printf("0x%02x", ch);
if ((ch = (unsigned char)fgetc(file)) != EOF)
printf("%02x", ch);
printf("\n");
}

Writing and reading CSV file in C wierd output

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.

Reading only first character of each line in file

I'm currently trying to read and process only first character in each line of a ".c" file. So far i have came to this code, but n is not even printed ot od the loop:
void FileProcess(char* FilePath)
{
char mystring [100];
FILE* pFile;
int upper = 0;
int lower = 0;
char c;
int n =0;
pFile = fopen (FilePath , "r");
do {
c = fgetc (pFile);
if (isupper(c)) n++;
} while (c != EOF);
printf("6");
printf(n);
fclose (pFile);
}
A few points:
You are not printing n correctly. You are feeding it to printf as the "formatting string". It is surprising that you get away with it - this would normally cause havoc.
You are reading one character at a time. If you want to print only the first character of each line, better read a line at a time, then print the first character. Use fgets to read entire line into a buffer (make sure your buffer is big enough).
Example (updated with inputs from #chux - and instrumented with some additional code to aid in debugging the "n=1" problem):
void FileProcess(char* FilePath)
{
char mystring [1000];
FILE* pFile;
int upper = 0;
int lower = 0;
char c;
int n =0;
pFile = fopen (FilePath , "r");
printf("First non-space characters encountered:\n")
while(fgets( myString, 1000, pFile) != NULL)
int jj = -1;
while(++jj < strlen(myString)) {
if ((c = myString[jj]) != ' ') break;
}
printf("%c", c);
if (isupper(c)) {
printf("*U*\n"); // print *U* to show character recognized as uppercase
n++;
}
else {
printf("*L*\n"); // print *L* to show character was recognized as not uppercase
}
}
printf("\n");
printf("n is %d\n", n);
fclose (pFile);
}
NOTE there are other more robust methods of reading lines to make sure you have everything (my favorite is getline() but it is not available for all compilers) . If you are sure your code lines are not very long, this will work (maybe make the buffer a bit bigger than 100 characters though)

Resources