confused by C syntax - c

i'm new at c.. and still having trouble at the syntax, hope you can help me... cause i'm stuck at this code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void){
FILE *stream = NULL;
stream = fopen("studentinfo.txt", "a+");
/*some of initialization were used for testing purposes only*/
char arr[5];
char arr2[5];
int i;
char name[3];
char course[5];
printf("enter details: ");
scanf("%s", arr2);
while(!feof(stream)){
fgets(arr, 100, stream);//i am confused if the line capture was stored at arr[0]
if(strcmp(arr, arr2)==0){//i want to compare
printf("success");//testing
}
printf("%s", arr);//i wonder does fgets just overwrites the new line to arr[0]
}
fclose(stream);
getch();
}
thanks guys...

You're opening studentinfo.txt for appending, but then reading from it (and you don't check the open succeeded
you've allocated 5 characters for arr, but read up to 100 characters into it with the fgets. This will overflow and cause memory corruption
you've allocated 5 characters for arr2, but read an arbitary number of characters into it - this will overflow and cause memory corruption
Fgets reads characters into memory starting at arr. arr[0] is the first character. &arr[0] is the same as arr
What's the getch() at the end for?
Also, "a+" positions the stream at the end of the file, so you won't be able to read anything.

if you have an existing file... and your file has data on it. then you could check if the data you typed is existing on the file or not. i'm not sure if this is what you want.
example if you typed... love
and the file also contains the exact word... love (on one line)
then it will print "success".
if the data you typed is not existing on the file, it will be appended on the file (on the next line).
int main(void){
char arr[5];
char arr2[5];
int i;
int n=0;
FILE *stream = NULL;
FILE *append = NULL;
stream = fopen("studentinfo.txt", "rt");
append = fopen("studentinfo.txt", "a+");
printf("enter details: ");
scanf("%s", arr2);
while(!feof(stream)){
fgets(arr, 6, stream);
if(strcmp(arr, arr2)==0){
printf("success");
} else n=-1;
}
if (n==-1){
fprintf(append, "%s\n", arr2);
}
fclose(stream);
fclose(append);
system("pause");
}

I am not sure why you are opening the stream with a+ because you never actually write to it. Maybe you want to make sure the file exists even if 0 length? You should still check that the open succeeded though.
You are then reading 100 characters into an array of just 5 bytes so you will get a serious memory overwrite if the file really does contain that number.
The scanf is unsafe too of course as the user may enter too many characters (they are actually limited to 4 because there is a NULL terminator that gets read).
At the end you appear to be writing the last line randomly if the user did not enter a matching line from the file.

Related

How to create 2D array from text file and print to new file in c

Wondering if I could get some advice. Firstly, I am very new to programming, so I apologise for any silly mistakes. Please feel free to point them out and I will try to go research to improve.
I feel I am doing something fundamentally wrong with my array.
I am trying to read in from a file whose filename is specified by user input, store the information from the file in a 2D array, which I then plan to print into another file, again defined by user input.
I am currently printing out the array, to check that it has been stored, but I believe I am using the 2D array incorrectly, as when I try to fprintf into my file, it just does not work.
Any advice would be greatly appreciated.
Thank you. Code as follows:
#include <stdio.h>
#include <string.h>
int main()
{
char finame[100];
printf("Enter file you would like to open: ");
scanf("%s", finame);
FILE *in = fopen(finame, "r");
char foname[100];
printf("Enter the filename you would like the output included in: ");
scanf("%s", foname);
FILE *out = fopen(foname, "w");
/*Char array to store string */
char str[50][20];
int i =0;
/*Loop for reading the file till end*/
while((fgets(str[i],sizeof(str[i]), in)) != NULL) {
fputs(str[i++],stdout);
//getchar();
}
return 0;
}
Avoid mixing fgets(), scanf() calls. scanf() leaves a newline character in the input buffer which is later consumed by fgets() (doesn't
matter in this case since input comes from a file not from stdin but a good practice overall).
There is also no protection for overflow, if you want to stick to scanf() add a width specifier and check the result to see if it succeeded.
if (scanf("%99s", finame) != 1) /* save one byte for \0 */
{
/* handle error case */
}
Check that you don't exceed the size of your array while writing to it.
Added 2 define directives that could clean your code up.
#define MAX_LINES 50
#define MAX_CHAR 20
char str[MAX_LINES][MAX_CHAR];
int i = 0;
while (i < MAX_LINES && (fgets(str[i], MAX_CHAR, in)) != NULL) /* always check if running out bounds */
{
fputs(str[i++], stdout);
}
The problem with the above code is that, if the file gets too big, you will end up missing data, what you could do is have a dynamic array and use a malloc / realloc approach to expand the array or a linked list.

Output file is filled with H symbols, C

I'm trying to write a program where I add words to one text file. Also, I can delete any word from this file and I save the result without this word to another text file. But when I run it, my second text file is filled with H symbols, and its size can be more than 100 mb. What's wrong with this code? Here it is:
int main(void)
{
int wordNumbers;
int i;
char buf[512];
char word[128];
FILE *o_file = fopen("C:\\atest.txt", "a");
FILE *s_file = fopen("C:\\btest.txt", "w");
printf("please add an amount of words of the dictionary ");
scanf("%i", &wordNumbers);
for (i=0; i< wordNumbers; i++)
{ char word[100] = {0};
printf("add a word into the dictionary please\n");
scanf("%s", &word);
fprintf(o_file, "%s\n", word);
}
if(!o_file || !s_file) return -1;
printf("please write down the word you want to delete\n");
scanf("%s",&word);
do
{
fscanf(o_file, "%511s", buf);
if(!strcmp(buf, word))
continue;
fprintf(s_file, "%s\n", buf);
}
while(!feof(o_file));
fclose(o_file);
fclose(s_file);
}
You print to the file o_file to insert your strings. Then, immediately after this, you start to read from this same file.
Read and write to a single file both use the same file pointer. Because the file pointer is here always at the very end of the file after these writes, the next read should fail – but since you don't check the result of fscanf, you don't ever realize that, and you write uninitialized data into the new file.
After writing the new contents into o_file, reset the file pointer to the start with fseek (o_file, 0, SEEK_SET) or rewind (o_file).
Always test if fscanf (and scanf) returns the correct number of recognized items. The return value is there for a reason.
Also read Why is “while ( !feof (file) )” always wrong?.

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 Magic Number from .au File

I wrote a small program to get the magic number from an .au file and print it to console, but every time I try, instead of getting the intended .snd, I get .snd$ instead.
I'm not sure why this is happening, considering that I'm only reading in 4 bytes, which is what the magic number is comprised of. So, where is the extra character coming from?
#include <stdio.H>
int main()
{
FILE *fin;
int r;
char m[4], path[20];
scanf("%s", path);
fin = fopen(path, "r");
r = fread(&m, sizeof(char), 4, fin);
printf("magic number is %s\n", m);
return 0;
}
You're printing it as though it were a string, which in C, means that it's NUL-terminated. Change your code like this and it will work as you expect:
char m[5];
m[4] = '\0'; /* add terminating NUL */
Also, you should be aware that scanf is a dangerous function. Use a command line argument instead.
The problem is not how you are reading.
The problem is that your variable is only 4 chars length, and it needs a null character to indicate the end.
printf with %s will print the content of the variable until reach a null character, until that it can print garbage if your variable is not correctly ended.
To fix you can have a bigger variable and set the [4] char with null.
How the new code should look like:
#include <stdio.H>
int main()
{
FILE *fin;
int r;
char m[5], path[20];
scanf("%s", path);
/*Scanf can be dangerous because it can cause buffer overflow,
it means that you can fill your variable with more bytes than it supports, which can end up being used for buffer overflow attacks:
See more: http://en.wikipedia.org/wiki/Buffer_overflow */
fin = fopen(path, "r");
r = fread(&m, sizeof(char), 4, fin);
m[4] = '\0';
printf("magic number is %s\n", m);
return 0;
}

trouble using fread in c

Im having some trouble figuring out how to properly format fread statements. The below code is just some randomn stuff Im practicing with. Basically it fills information into the first array (s), writes 's' to a file, and then reads the file into the second array (s2). However I can't seem to get the fread statement formated in a way that doesnt give an error or return garbage. The arrays are in char datatype because, if my understanding is correct, char uses less memory than other datatypes. The eventual application of this practice code is for a data compression project.
#include<stdio.h>
#include<string.h>
FILE *fp;
//file pointer
char s[56];
//first string
char s2[56];
//target string for the fread
int n=0;
//counting variable
int m=0;
int main (void)
{
fp=fopen("test.bin", "w+");
//open a file for reading and writing
strcpy(s, "101010001101010");
//input for the string
for(n=0;n<56;n++)
{
if(s[n]==1)
m=n;
else if(s[n]==0)
m=n;
}
printf("%d\n", m);
//the above for loop finds how many elements in 's' are filled with 1's and 0's
for(n=0;n<m;n++)
{
printf("%c", s[n]);
}
//for loop to print 's'
fwrite(s, m, 1, fp);
//writes 's' to the first file
s2=fread(&s2, m, 1, fp);
//an attempt to use fread...
printf("\n\ns2\n\n");
for(n=0;n<m;n++)
{
printf("%c", s2[n]);
}
printf("\n");
//for loop to print 's2'
fclose(fp);
printf("\n\n");
printf("press any number to close program\n");
scanf("%d", &m);
}
A FILE structure has an implicit seek position within the file. You read and write from that seek position. If you want to read what you have written, you need to change the seek position back to the beginning of the file with a call to fseek(). In fact, for a file open for reading and writing, you must call fseek() when switching between reading and writing.
The return value of the fread function is of type size_t. It is the number of elements successfully read. (reference: http://www.cplusplus.com/reference/cstdio/fread/)
Don't assign it to s2. Simply use fread(&s2, m, 1, fp);

Resources