Not Getting Output in File - c

#include <stdio.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
f1 = fopen("C://Users//Lenovo//Desktop//fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
else
{
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
}
printf("\nCorrect answer: ");
scanf("%d", corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
}
}
fclose(f1);
return 0;
}
I have been trying to create a Javascript generator as you can see in the code.
The main problem i am getting is inside the while loop.
The while loop is terminating after only one iteration and the program not writting the data in the created file. The file already exists.
I am not getting where is the problem occuring.

You need to cleanse your input of new-lines. You also had a redundant Else statement, and Scanf requires the address of a variable, not it's value.
This should work for you. You can check out this question here: Fgets skipping inputs, which I shamelessly copied.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
int c;
char *p;
f1 = fopen("fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
if ((p=strchr(q, '\n')) != NULL) *p = '\0';
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
if ((p=strchr(opt[i], '\n')) != NULL) *p = '\0';
}
printf("\nCorrect answer: ");
scanf("%d", &corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
while ( (c = getchar()) != '\n' && c != EOF );
}
fclose(f1);
return 0;
}

Related

Stack smashing in file io in c

void issueBook(){
printf("Hii!\n");
//printf("Enter your student ID: ");
//int stdID;
//scanf("%d", &stdID);
printf("Enter the book ID\n");
int bookID;
scanf("%d", &bookID);
FILE *in_file = fopen("recordLib.txt", "r");
FILE *fp = fopen("temp.txt", "w");
struct stat sb;
stat("recordLib.txt", &sb);
char *file_contents = malloc(1024);
int mark = 0;
char ID[] = "";
while (fscanf(in_file, "%[^\n] ", file_contents) != EOF) {
int size = strlen(file_contents);
int countCom = 0;
char ID[] = "";
//printf("%d\n", size);
if(mark == 0){
for(int i=0; i<size; i++){
//printf("asdfsd\n");
//printf("%c", file_contents[i]);
if(countCom == 0 && (file_contents[i] != ',')){
strncat(ID, &file_contents[i], 1);
//printf("%c\n", file_contents[i]);
}
else if(atoi(ID) != bookID){
break;
}
else if((file_contents[i] == ',') && (countCom < 3) && (atoi(ID) == bookID)){
//printf("%c\n", file_contents[i]);
//printf("%s\n", ID);
countCom++;
}
else{
//printf("%c\n", file_contents[i]);
if(file_contents[i] == '1'){
printf("Sorry!! someone has already issued the book");
mark = 2;
break;
}
else if(file_contents[i] == '0'){
file_contents[i] = '1';
mark = 1;
break;
}
}
}
}
fwrite(file_contents, 1, size, fp);
fwrite("\n", 1, 1, fp);
}
fclose(fp);
fclose(in_file);
remove("recordLib.txt");
rename("temp.txt", "recordLib.txt");
//printf("%d\n", s);
//if(mark == 1){
// updateStu();
//}
free(file_contents);
}
I have made this function which takes the bookID from the user and then searches for it in the file:
Searching: It reads line by line and as we already know till first comma ',' it would be book ID so it will store in another string and then convert it to int. Now it will compare it with entered ID if it matches then it will update the 0 at the end to 1, else move to next line.
Error: I always getting stack smashing error when the function again returns to the main function. I am unable to find the thing that is causing the error. Also that when I run in VS code, it runs successfully but in Linux this problem occurs! Please help. Thanks in advance.

How to give access to text file using if statement?

I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}
You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.
int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}
The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}

How to read a file into an array of structs?

Im trying to read a text file into an array of structs, but when trying to print the array, the struct is empty. The printing function works fine and I think the problem is in getRawData.
struct student
{
char ID[MAXID + 1];
char f_name[FIRST_NAME_LENGTH + 1];
char s_name[LAST_NAME_LENGTH + 1];
int points[MAXROUNDS];
};
//main//
case 'W':
if(save(array, len) == 0);
{
printf("Data saved.\n");
}
break;
case 'O':
if(getRawData(array, len));
{
printf("File read.\n");
}
break;
int save(struct student *h, int num_students)
{
char name[20];
printf("Enter file name: " );
scanf("%s", name); // Read in filename
FILE *output = fopen(name, "w"); // open the file to write
if (!output) {
return -1; // error
}
for (int i = 0; i < num_students; ++i)
{
fprintf(output, "%s %s %s \n", h[i].f_name, h[i].s_name, h[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fprintf(output, "%d\n", h[i].points[j]);
}
printf("Information of student %s %s (%s) written into file %s\n", h[i].s_name, h[i].f_name, h[i].ID, name);
}
fclose(output); // close
return 0;
}
int getRawData(struct student *records)
{
int i;
int nmemb; // amount of structs
char name[20];
printf("Name of the file to be opened: \n");
scanf("%s", name);
FILE *outtput = fopen(name, "r");
int ch=0;
int lines=0;
if (outtput == NULL);
return 0;
lines++;
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
{
lines++;
}
}
nmemb = lines / 7;
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fscanf(outtput, "%d\n", &records[i].points[j]);
}
}
printf("%d", lines);
return i;
}
So my goal is to get the data from the file and write it over whatever there is stored in the struct array. I would appreciate some help as I have been working on this for way too long.
Look at this code in getRawData(), first you are reading file to identify total number of lines:
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
.....
.....
due to this the file stream pointer pointing to EOF and after this, in the for loop, you are doing:
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
.....
.....
Here, the fscanf() must be returning the EOF because there is nothing remain to read from stream file. You should check the return value of fscanf() while reading file.
You should reset the pointer to start of file before reading it again. You can use either rewind(ptr) or fseek(fptr, 0, SEEK_SET). Below is a sample program to show you what is happening in your code and how the solution works:
#include <stdio.h>
int main (void) {
int ch;
int lines = 0;
char str[100];
FILE *fptr = fopen ("file.txt", "r");
if (fptr == NULL) {
fprintf (stderr, "Failed to open file");
return -1;
}
while (!feof(fptr)) {
ch = fgetc (fptr);
if(ch == '\n') {
lines++;
}
}
printf ("Number of lines in file: %d\n", lines);
printf ("ch : %d\n", ch);
printf ("Now try to read file using fscanf()\n");
ch = fscanf (fptr, "%s", str);
printf ("fscanf() return value, ch : %d\n", ch);
printf ("Resetting the file pointer to the start of file\n");
rewind (fptr); // This will reset the pointer to the start of file
printf ("Reading file..\n");
while ((ch = fscanf (fptr, "%s", str)) == 1) {
printf ("%s", str);
}
printf ("\nch : %d\n", ch);
fclose (fptr);
return 0;
}
The content of file reading in the above program:
Hello Vilho..
How are you!
Output:
Number of lines in file: 2
ch : -1
Now try to read file using fscanf()
fscanf() return value, ch : -1
Resetting the file pointer to the start of file
Reading file..
HelloVilho..Howareyou!
ch : -1
Here you can see, the first ch : -1 indicate that the file pointer is at EOF and if you try to read you will get EOF because there is nothing left to read. After resetting file pointer, you can see fscanf() is able to read file.
You should not use while (!feof(file)). Check this.

Trouble with C program that reads a MIPS instructions, outputs file with line number, and summary

The problem: Use a c program to read a MIPS instruction file, output it to a second file (both are command line arguments) which contains the contents of the MIPS file, with line numbers. The second half is supposed to display a cross reference table, which details the identifier, the definition(a number), and the usage of that identifier, by line number, for any identifier used more than once.
Unfortunately, I've run aground, and the program not only doesnt seem to actually print anything, but it doesnt seem to make any files either. This is a bit of a last ditch effort, to see if anyone else can help me out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Func line takes in a file, and places a line number at the beginning of every
non blank line */
void line(FILE *input, FILE *output) {
char a, c;
int lineNum = 0;
int startOfLine = 1;
char ch;
fprintf(output, "%d ", ++lineNum);
//copy the contents of the input file into the output file
do {
a = fgetc(input);
fputc(a, output);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(output, "%d ", ++lineNum);
else
fprintf(output, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
printf("ran line: \n");
}
/* Func cross takes in a file, and finds each identifier, marks its definition, and every
use and returns that in the output file */
void cross(FILE *input, FILE *output) {
FILE *temp = fopen("temp.txt", "a+");
int lineNum = 0;
int startOfLine = 1;
char identifier[20][10];
char a, c, i;
int j, k, p;
int size=0;
int def[20];
int use[20][50];
char tempstr[80];
fprintf(output, "Identifier\tDefinition\t Use\n");
fprintf(temp, "%d ", ++lineNum);
//copy contents of input into a temp file
do {
a = fgetc(input);
fputc(a, temp);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(temp, "%d ", ++lineNum);
else
fprintf(temp, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
fclose(temp);
fopen("temp.txt", "r");
j=0;
//checks to see if current line has an Identifier and if so saves it to an array
//along with the line number it was defined on
while(fgets(tempstr, 80, temp)) {
if(isalpha(tempstr[4]) || tempstr[4] == '_') {
sscanf(tempstr, "%d %[0-9_A-Z_a-z_]", &def[j], identifier[j]);
j++;
size++;
}
}
fclose(temp);
fopen("temp.txt", "r");
//checks for each identifier, on every line whether or not that identifier is used
while(fgets(tempstr, 80, temp)) {
char *tempNum;
sscanf(tempstr, "%s", tempNum);
int tempN = atoi(tempNum);
int n;
p=0;
for(n=0; n<size; n++) {
if(strstr(tempstr, identifier[n]) && tempN > def[n] && tempstr[4] != '#') {
use[n][p] = tempN;
p++;
}
}
}
//writes the identifier, definition, and uses to the file
for(k=0;k<size;k++) {
fprintf(output, "%s\t\t %d\t\t ", identifier[k], def[k]);
for(p=0; p<50; p++) {
if(use[k][p] != NULL && use[k][p] < lineNum && use[k][p] > def[k])
fprintf(output,"%d ", use[k][p]);
}
fprintf(output, "\n");
}
printf("ran cross: \n");
}
/*Func both returns the file with numbered lines and a cross reference table at the bottom of the file */
void both(FILE *input, FILE *output, char *outputName) {
FILE *lineFile = fopen("line.txt", "a+");
FILE *crossFile = fopen("cross.txt", "a+");
char ch;
line(input, lineFile);
cross(input, crossFile);
while( (ch = fgetc(lineFile)) != EOF)
fputc(ch, output);
fprintf(output, "\n\t\t\tCross Reference Table\n");
while( (ch = fgetc(crossFile)) != EOF)
fputc(ch, output);
fclose(output);
printf("ran both: \n");
}
int main(int argc, char * argv[]) {
FILE *input, *output;
output = fopen(argv[4], "a+");
char outputName[50];
strcpy(outputName, argv[4]);
//Error testing
if(argc > 5)
exit(1);
if(strcmp(argv[2], "-l") != 0 && strcmp(argv[2], "-c") != 0 && strcmp(argv[2], "-b") != 0) {
printf("Incorrect flag syntax... Exiting\n");
exit(1);
}
if((input = fopen(argv[3], "r+")) == NULL) {
printf("Input file could not be opened... Exiting\n");
exit(1);
}
else {
if(strcmp(argv[2], "-l") == 0) {
line(input, output);
}
else if(strcmp(argv[2], "-c") == 0)
cross(input, output);
else {
both(input, output, outputName);
}
}
printf("ran main: \n");
return 0;
}

C programming, clearing a string

So I have some code that gets a user input and compares it in a loop, it will check the first line, then the second, then the third and so on, however the program doesn't get another clean string variable for the next cycle of the loop, as shown here:
char text[100], blank[100];
int c = 0, d = 0;
void space(void);
int main()
{
int loop=0;
char str[512];
char string[512];
int line=1;
int dis=1;
int score=0;
char text[64];
FILE *fd;
fd = fopen("Student Usernames.txt", "r"); //Should be test
if (fd == NULL)
{
printf("Failed to open file\n");
exit(1);
}
do
{
printf("Enter the string: ");
gets(text);
while (text[c] != '\0')
{
if (!(text[c] == ' ' && text[c] == ' ')) {
string[d] = text[c];
d++;
}
c++;
}
blank[d] = '\0';
printf("Text after removing blanks\n%s\n", string);
getch();
for(loop = 0;loop<line;++loop)
{
fgets(str, sizeof(str), fd);
}
printf("\nLine %d: %s\n", dis, str);
dis=dis+1;
str[strlen(str)-1] = '\0';
if(strcmp(string,str) == 0 )
{
printf("Match\n");
score=score+2;
}
else
{
printf("Nope\n");
score=score+1;
}
getch();
}
while(!feof(fd));
printf("Score: %d",score);
getch();
}
For example: Input: Apple (1st word) , 1st line = Apple, Match, Input: Banana, 2nd line = Applea
Clearly the program has added onto to first input, I want to know how to change this
Edit: Upon reseting c and d back to 0 after each loop the output is now "AppleBanana"

Resources