Errorneous output while reading File in C - 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.

Related

C - print file using system calls?

I'm trying to get aquainted with system calls and C. I'm trying to read a file and write all the contents to the command line. I'm trying
int handle = open("./test.txt", O_RDONLY, O_TEXT);
char buf[1];
lseek(handle, 0, SEEK_SET);
while (0 != read(handle, buf, 1)) {
printf(*buf);
}
This ALMOST works, except that it adds some gibberish characters after each character read from the file. For example if the file contains asd asd this writes a:_s:_d:_ :_a:_s:_d to the console. Any idea why? How can I fix it?
You code should produce warnings on most modern compilers. Because printf() doesn't accept a char. Since you are reading the file char by char, you can instead use putchar() to print on the stdout.
while (read(handle, buf, 1) == 1) {
putchar(buf[0]);
}
Every string has to end with the \0 (null) character.
So try to make your buffer size 2, and just before printf do buf[1] = '\0';
In general when you read wcnt (type ssize_t) number of chars you do buf[wcnt] = '\0';
Also your printf is not syntaxed correctly safely!
printf("%s", buf);
Edit: As mentioned in other answers and comments (I will not add it since I did not propose it first), you can just print a char in this case.

Trying to read formatted file in C

i'm trying to read a formatted file in C this is a sample line of the file:
SURNAME;NAME;MINUTES'SECONDS''ONE-HUNDREDTHS OF A SECOND
I wrote this code:
while(!feof(fp))
{
fscanf(fp,"%[^;]s",surname);
fscanf(fp,"%c",&c);
fscanf(fp,"%[^;]s",name);
fscanf(fp,"%c",&c);
fscanf(fp,"%d'%d''%d",&min,&sec,&sec_cent);
fscanf(fp,"\n");
}
It works well with the name and surname strings, but it doesn't extract the time MINUTES'SECONDS''ONE-HUNDREDTHS OF A SECOND and i don't know why
Can someone help me?
There are a couple of things you may want to change in your code:
Always check the return value of scanf (or fscanf) to see if all the data were read.
Don't use feof() to control a loop.
You don't need to extract the '\n' with scanf, unless you are going to use getline() afterwards.
You don't need the s too, with that format specifier, but you should prevent buffer overflows limiting the number of chars read for each field.
You can use the modifier %*c to skip a char (the ;).
This should be fine:
int min = 0, sec = 0, sec_cent = 0;
char name[128], surname[128];
while ( fscanf(fp, "%127[^;]%*c%127[^;]%*c%2d'%2d''%2d", surname, name,
&min, &sec, &sec_cent) == 5 ) {
// do something...
}

New to C, trying to better understand char arrays, pointers, reading in files, etc

Alright, so I am working on linux and emacs for the first time using C, and coming from pretty beginner level java programming in eclipse, my new CS course is really daunting. SO much stuff has been thrown at me as if I already knew it...
Anyway, the current part of my assignment I am working on involves reading in text from a file (doing that by piping a text file as standard input into my program). Currently I had three functions, a main function where I read in the file / call other functions, a function that reverses the order of a single word (apple becomes elppa) with *char beg and *char end as parameters, and a function that reverses the order of every word in a line of words, calling the previous function and taking a char *str as a parameter.
I am having trouble reading in the files in my main method in a way that makes it easy to utilize these functions. Here's a snippet of how I am reading them in currently, but as you can see I haven't figured out a way to store a line of words and send that into my function (I need to reverse line by line, so I can't just add every single char to one long array)
enter code here``
char line[8192]
int location = 0;
FILE *in = stdin;
int buff = 0;
while (buff = fgetc(in))
{
fprintf(stderr, "Character is: %d '%c' \n", buff, (char)buff);
if (buff == EOF)
{
break;
}
line[location] = (char)buff;
location++;
}
line[location] = '\0';
If you want to get a whole line, you can do this:
char line[MAX_LINE_SIZE];
fscanf(in, "%[^\n]", line);
//do whatever you need with the line
fscanf(in, "%[\n]", line);
The first fscanf call reads a whole line and store in variable line.
But it doesn't skip that line! If you use it again, it will store the very same line.
The second fscanf call is for this: it stores '\n' in variable line and skips the line you read previously.
If you want, you can create another buffer to get the '\n' and skip the line:
char garbage[2];
fscanf(in, "%[\n]", garbage);
I hope this helps.

How to save every line in file (IN C) in a variable? :)

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.

Read whole digits not split

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;
}

Resources