Read whole digits not split - c

Hi guys how to read entire digits from file? I mean my input file is 100-4/2 and i wrote this code while(fscanf(in,"%s",s)!=EOF) but it read like this 1 0 0. I want read like 100. How to solve this?

It's probably because you are using one-byte character(ANSI) set while the file is written with two-byte characters(Unicode). If you have created the file with the same program that is reading it it's going to read it right, but if not, you can open the file you are reading in notepad, then click save as, and there you can choose ANSI or Unicode.

You can read the whole line at once using getline() or similar method (also you can read as you are doing if there is only one line, then when EOF is true, whole line is read). Then you can parse the line to extract numbers and operators.

Use "%d" for integers
int value;
if (scanf("%d", &value) != 1) /* error */;
printf("Value read is %d.\n", value);

The below is simple program is self explanatory, which reads a file character by character, for each iteration stores this character into a temporary variable temp. and when the value in temp is a numerical character it simply copies this value in array named s.
int main()
{
char s[10]="\0";//initialzing array to NULL's and assuming array size to be 10
int i=0,temp=0;
FILE *fp=fopen("t.txt","r"); //when file has 100-4/2
if(fp==NULL)
{
printf("\nError opening file.");
return 1;
}
while( (temp=fgetc(fp))!=EOF && i<10 ) //i<10 to not exceed array size..
{
if(temp>='0' && temp<='9')//if value in temp is a number (simple logic...)
{
s[i]=temp;
i++;
}
}
printf("%s",s);//outputs 10042
return 0;
}

Related

Scanf not reading all numbers found in CSV in C

I am trying to read a CSV file of integers and count their number. However, the code executes this while loop once.
When i change the format of the file so that each number is on a separate line and no commas are there, it works. Can someone tell me where is my mistake? How can i make the loop work for CSV?
while(scanf("%d", &otherNum)==1)
{
count++;
printf("%d", otherNum);
}
As soon as "%d" hits a non-integer (comma, or any other character), it exits the while loop.
You will need to build the logic of parsing between "%d" and other characters inside of your loop.
Better use below codes
char num[50];
int otherNum = 0;
FILE *f = fopen("yourCSV.csv", "w");
while(fgets(num,sizeof num,f){
if(num[0] != ',')
{
otherNum = atoi(num);
printf("%d", otherNum);
}
}

Errorneous output while reading File in C

I am trying to write a string to a file and then read the string and output the string written into the file.
For example
INPUT (Input Name)
FalconHawk
OUTPUT
Hi FalconHawk! Have a great day!
My code is:
#include<stdio.h>
void main(){
char n[10],r[1000];
FILE *fptr,*fpt;
scanf("%s",n); //Input name
fptr=fopen("welcome.txt","w");
fprintf(fptr,"%s",n); //Write to file
fclose(fptr);
fpt=fopen("welcome.txt","r");
fscanf(fpt,"%s",r);
printf("Hi %s! Have a good day.",r); //Output file content
fclose(fpt);
}
But because of some reason I am getting an output like
INPUT (Input Name)
FalconHawk
OUTPUT
HiHi FalconHawk! Have a great day! //"Hi" is getting printed two times
On replacing "Hi" with "Welcome" I am getting an output like
OUTPUT
WelcomeWelcome FalconHawk! Have a great day! //"Welcome" is getting printed two times.
What is causing this issue?
Your buffer is too small and there's no room for the terminating null byte, therefore, your code invokes undefined behavior. If you want to read 10 characters, then this is how you should do it
char input[11];
if (scanf("%10s", input) == 1) {
// Safely use `input' here
}
And if you want to read an entire line of text from stdin then use fgets() instead
if (fgets(input, sizeof input, stdin) != NULL) {
// Safely use `input' here
}
Strings in c always need an extra byte of space to store the terminating '\0', read a basic tutorial on strings in c to learn how they work and how to treat them.

Getting garbage value in structure when reading from file

I have a text file like this
987jgkfl
12358ldjkdju
7579jngj
8uuujkl
09698fjfj
I have a structure like this
struct emprec
{
int empid;
int todo;
char name[20];
};
I write the values of the struct into file like this
fd = fopen("/home/tarun/Desktop/test34.txt","a+");
fprintf(fd,"%d",temp2.empid);
fprintf(fd,"%s",temp2.name);
count++;
fclose(fd);
But when i read from the file i am getting the garbage value
while(i<=count)
{
fread(&temp5,sizeof(temp5),1,fd);
//fscanf(fd,"%d,%s",&temp5.empid,temp5.name);
//int k = strlen(temp5.name);
//printf("Value of k is %d\n",k);
//temp5.name[7]= '\0';
//fread(&temp5.empid,sizeof(temp5.empid),1,fd);
//fread(temp5.name,20,1,fd);
printf("\n%d %s",temp5.empid,temp5.name);
i++;
}
fclose(fd);
Please tell me where am i going wrong
Like say nemetroid :
You're writing a textual representation (with
fptrinf) of your struct but attempting to read a binary representation
(with fread).
For example, suppose you want write an int in a file. By doing like this :
fd = fopen("file","a+");
fprintf(fd,"%d",42);
You will write the character '4' and the character '2'. In ASCII, '4' is 0x34 and '2' is 0x32.
If you want to read that file and try to put it in an 4 bytes integer by doing like this :
int a = 0;
fread(&a,sizeof(a),1,fd);
The variable 'a' will contain the data on the file :
a = 0x00003234
And not 42 (0x0000002a) as you expect.
There were some calls that was missing from your code:
fflush()
Used to flush the file's buffer, you have to call this if you performed writes to the file and now you want to read
fseek
Used to set the file position indicator. In your case, the file position indicator was at the end of the file. Use fseek() to set the file position to where you started writing and than start reading.
fscanf function corresponds to fprintf. fread corresponds to fwrite. It means if you want to dump the structure using fprintf, then read it using fscanf. if you want to read the structure using fread then dump it using fwrite. Referring manpages of these functions should help.

read text file and store in array in c programming

I want read text file and store in array then show.
This is my code:
int i = 0, line = 5;
char ch[100];
FILE *myfile;
myfile = fopen("test.txt","r");
if (myfile== NULL)
{
printf("can not open file \n");
return 1;
}
while(line--){
fscanf(myfile,"%s",&ch[i]);
i++;
printf("\n%s", &ch[i]);
}
fclose(myfile);
return 0;
}
This is my text:
test 123562
856
59986
But result:
est
2356
56
9986
What is wrong? :(
ch[i] is holding a single character. Statement fscanf(myfile,"%s",&ch[i]); will scan string to ch[i] which can hold only one character. There is no place for '\0' which leads your program to undefined behavior.
Change
fscanf(myfile,"%s",&ch[i]);
to
fscanf(myfile,"%s",ch);
Previous answer was wrong. Behavior of program is well defined but you are scanning the file in a wrong manner. Your program will work as expected if you place i++; after printf statement.
while(line--){
fscanf(myfile,"%s",&ch[i]);
printf("\n%s", &ch[i]);
i++;
}
The reason is that &ch[i] is a pointer to the ith element of the array and string will be stored in array starting at position i. For the input given, this will work because the given array is large enough to hold the string.
You can do this as:
while(line--){
fscanf(myfile,"%s",ch);
printf("\n%s", ch);
i++;
}
but it will overwrite the array ch each time a string is scanned to it. Better to use a two dimensional array to store strings and read file with fgets.
You're not going to be able to fit five lines in the single char ch[100] array; that's just an array of 100 characters.
You can make it an array of arrays, i.e. char ln[5][100] which will give you room for five lines of 100 characters each.
Then you of course need to index into that array in the loop, i.e.:
for(int i = 0; i < 5; ++i)
{
if(fgets(ln[i], sizeof ln[i], myfile) == NULL)
{
fprintf(stderr, "Read error on line %d\n", i);
exit(1);
}
}
This uses fgets() which is much better suited at reading in whole lines; fscanf() will stop at whitespace with %s which is seldom what you want.
There is no need to use the ampersand in the scanf while getting the string. Make that into like this.
fscanf(myfile,"%s",&ch[i]);
to
fscanf(myfile,"%s",ch);
&ch[i] It will get the character for i th position in that array. If you want to get like that you can use the %c instead of %s. And change this one to.
printf("\n%s", ch);
While printing the string when you use the ampersand(&) that will access the address of that variable.
The program developed must be able to read the input files containing matrix A and matrix B
using fopen function
a. Matrix A and B of different size may be stored in different input file (if required).
Scan and assign matrix A and B as array using fscanf function and for loop
Perform matrix operations
a. Add matrix A and B
b. Subtract matrix A and B
c. Multiply matrix A and B
Use conditional statement if or switch for switching between 3, 4 and 5 elements matrix.
Print all input matrices and results obtained in a new file called output.dat using fprintf
function.
The output.dat file must have a header with the following information:
a. Student name
b. Student matric number
c. Class section
d. Lecturer name
e. Project title
Below the header, the output file must contain matrix A and B and the results from matrix
operation.
Use matrix A and B as given below:

How do I read a file in C and store the characters in a variable

I am completely new to C and need help with this badly.
Im reading a file with fopen(), then obtaining the contents of it using fgetc(). What I want to know is how I can access the line fgetc() returns so if I can put the 4th - 8th characters into a char array. Below is an example I found online but am having a hard time parsing the data returns, I still don't have a firm understanding of C and don't get how an int can be used to store a line of characters.
FILE *fr;
fr = fopen("elapsed.txt", "r");
int n = fgetc(fr);
while(n!= EOF){
printf("%c", n);
n = fgetc(fr);
} printf("\n");
Here
1 first open the file
2 get size of file
3 allocated size to character pointer
4 and read data from file
FILE *fr;
char *message;
fr = fopen("elapsed.txt", "r");
/*create variable of stat*/
struct stat stp = { 0 };
/*These functions return information about a file. No permissions are required on the file itself*/
stat("elapsed.txt", &stp);
/*determine the size of data which is in file*/
int filesize = stp.st_size;
/*allocates the address to the message pointer and allocates memory*/
message = (char *) malloc(sizeof(char) * filesize);
if (fread(message, 1, filesize - 1, fr) == -1) {
printf("\nerror in reading\n");
/**close the read file*/
fclose(fr);
/*free input string*/
free(message);
}
printf("\n\tEntered Message for Encode is = %s", message);
PS Dont Forget to Add #include <sys/stat.h>.
You're not retrieving a line with fgetc. You are retrieving one character at a time from the file. That sample keeps retrieving characters until the EOF character is encountred (end of file). Look at this description of fgetc.
http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/
On each iteration of the while loop, fgetc will retrieve a single character and place it into the variable "n". Something that can help you with "characters" in C is to just think of it as one byte, instead of an actual character. What you're not understanding here is that an int is 4 bytes and the character is 1 byte, but both can store the same bit pattern for the same ASCII character. The only different is the size of the variable internally.
The sample you have above shows a printf with "%c", which means to take the value in "n" and treat it like an ASCII character.
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
You can use a counter in the while loop to keep track of your position to find the 4th and 8th value from the file. You should also think about what happens if the input file is smaller than your maximum size.
Hope that helps.
Ok look at it as box sizes I could have a 30cm x 30cm box that can hold 1 foam letter that I have. Now the function I am calling a function that 'could' return a 60cm x 60cm letter but it 99% likely to return a 30cm x 30cm letter because I know what its reading - I know if I give it a 60cm x 60cm box the result will always fit without surprises.
But if I am sure that the result will always be a 30cm x 30cm box then I know I can convert the result of a function that returns aa 60cm x 60cm box without losing anything

Resources