i don't know what to do, i'am try 10 minutes to fix it, but nothing.
i'am a beginner... so... don't dislike somfthing.
Please help me with code :D
i working with C one month and it is cool language.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *pf;
char input[500];
char ime[500];
int ime2;
for(ime2 = 0; ime2 >= 9999999; ime2++);
/*
ime2 is: 1,2,3,4,5,6,7,8,9,10,11,12... 9999999
*/
pf = fopen("bruteforce.txt","w");
if(pf == NULL){
printf("Datoteka (.txt) po imenu: bruteforce nije pronadjena!\n");
} else {
printf("Sledeci text ce biti unesen: \n");
gets(input);
ime = input + ime2; // error
fputs(ime, pf);
printf("Uspesno je ispisano.\n");
fclose(pf);
}
system("pause >nul");
return 0;
}
First of all change
gets(input)`
to
fgets(input, sizeof(input), stdin)
and then try this
snprintf(ime, sizeof(ime), "%s %d", input, ime2);
BTW: maybe MSVC will not like snprintf() as is, they just add an underscore like this
_snprintf(ime, sizeof(ime), "%s %d", input, ime2);
Related
This program should ask you to add member (people) to a struct and print them on a file but after the first for loop just stop working and jump over the name part. I just found that thing that allow you to add space to a string, tried it but no success...
I tried to remove it and it work without any problem so the [^\n] make something go wrong.
What is wrong ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Staff {
char Surname[100];
char Name[100];
int age;
char spec[100];
int id;
} person;
void write();
void leggi();
void trova();
int main() {
write();
}
void write() {
int i = 0;
int n = 1;
int r;
FILE *fp;
fopen_s(&fp, "index.txt", "w+");
if (fp == NULL) {
printf("Failed to open file\n");
exit(1);
}
fprintf(fp, "%d\n", i);
for (i = 0; i < n; i++) {
printf("Surame:\n");
scanf_s("%[^\n]s", person.Surname, 100);
fprintf(fp, "%s\t\t", person.Surname);
//loop just get over the name part
printf("Name:\n"); //after the first loop
scanf_s("%s", person.Name, 100);
fprintf(fp, "%s\t", person.Name);
printf("Age:\n");
scanf_s("%d", &person.age);
fprintf(fp, "%d\t", person.age);
printf("Specialization\n");
scanf_s("%s", person.spec, 100);
fprintf(fp, "%s\n", person.spec);
printf("Want to enter another? 1=yes 0=no...\n");
scanf_s("%d", &r);
if (r == 1)
n = n + 1;
}
rewind(fp);
fprintf(fp, "%d\n", i);
fclose(fp);
}
There are multiple problems in your code:
you use the so called secure functions fopen_s, scanf_s etc, but you do not check the return values to detect invalid input. You should instead use standard functions, pass the appropriate arguments and check the return values.
using scanf_s is actually non portable: the scanf_s function defined in Annex K of the C Standard requires the length argument after the pointer to have size_t type, whereas the function with the same name in the Microsoft library uses type UINT, which has a different representation on 64-bit versions of their Windows OS. A classical case of the Embrace, enhance and extinguish strategy. In Standard C, one should write: scanf_s("%s", person.Name, (size_t)100) or better:
scanf_s("%s", person.Name, sizeof person.Name)
there is no need to open the output file for update with "w+", just use "w".
you rewind the stream pointer back to the beginning of file and overwrite the number of entries at the start of the file. This works as long as you have less than 10 entries, but beyond that, the number has more digits so some characters in the file will be corrupted. You could use a format with padding such as "%6d\n" which would allow for up to 1 million records without risks.
"%[^\n]s" is not a correct scanf format: you should just write "%[^\n]" or better " %99[^\n]" to skip initial white space and limit the input to 99 characters.
Here is a modified version:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Staff {
char Surname[100];
char Name[100];
int age;
char spec[100];
int id;
};
void write(void);
void leggi(void);
void trova(void);
int main() {
write();
}
int flush_input(void) {
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
return c;
}
void write(void) {
int n = 0;
int r;
FILE *fp = fopen("index.txt", "w");
if (fp == NULL) {
fprintf("Failed to open file index.txt: %s\n",
strerror(errno));
exit(1);
}
fprintf(fp, "%6d\n", n);
for (;;) {
struct Staff person = { 0 };
printf("Surname:\n");
if (scanf(" %99[^\n]", person.Surname) != 1)
break;
flush_input();
fprintf(fp, "%s\t\t", person.Surname);
//loop just get over the name part
printf("Name:\n"); //after the first loop
scanf(" %99[^\n]", person.Name);
flush_input();
fprintf(fp, "%s\t", person.Name);
printf("Age:\n");
scanf("%d", &person.age);
flush_input();
fprintf(fp, "%d\t", person.age);
printf("Specialization\n");
scanf(" %99[^\n]", person.spec, 100);
flush_input();
fprintf(fp, "%s\n", person.spec);
n++;
printf("Want to enter another? 1=yes 0=no...\n");
if (scanf("%d", &r) != 1 || r != 1) {
flush_input();
break;
}
flush_input();
}
rewind(fp);
// update the entry count on 6 characters
fprintf(fp, "%6d\n", n);
fclose(fp);
}
Change the call of scanf below for entering strings by inserting a space in the beginning of the format string. For example instead of this call
scanf_s("%[^\n]s", person.Surname, 100);
(where the letter s must be removed from the format string) write
scanf_s(" %[^\n]", person.Surname, ( rsize_t )100);
^^^^^^^^
This allows to skip leading white space characters in the input buffer.
Pay attention to that changing the condition or the for loop the was as you are doing
for (i = 0; i < n; i++) {
//...
if (r == 1)
n = n + 1;
}
makes the code unclear. Instead of the for loop you could use do-while loop.
In this code, whenever I try to use scanf to input values, it works but fgets which I want to use do not work and just allow me to input my name. It is not allowing me to further input my date of birth and account? How to make it work?
#include<stdio.h>
#include <stdlib.h>
int main() {
static const char* listing[] = {"Name","Date of Birth", "Account"};
int i, done=0;
char data[3][21];
FILE * fw = fopen("new.csv", "a");
for (i=0; i<3; i++){
printf("Enter your %s: ", listing[i]);
// fgets(data[i], 50, stdin);
if(scanf("%s", data[i]) != 1){
done = 1;
break;
}
}
if(!done){
fprintf(fw, "%s, %s, %s", data[0], data[1], data[2]);
}
fclose(fw);
return 0;
}
Because fgets function returns the first parameter which is data[i] in your example. So you can change your code like that .
if(fgets(data[i], 50, stdin) == NULL){
done = 1;
break;
}
else {
data[i][strlen(data[i])-1]='\0';
}
}
`
Because in failure fgets returns null.If you want to write them horizontally, you should write this else statement too because fgets reads newline character too. You can solve this problem like that. However don't forget to include #include <string.h> library because you use strlen function.
I've been trying to do file excercises in C but when I run programs from the professor or tutorials (which should work), the file always comes out blank. Is there a solution to this?
My computer is pretty old, but it can still run various programs, I don't undersand why it doesn't work with files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*program that prints on a file your shopping list*/
int main(int argc, char **argv)
{
FILE *fp= fopen("Shopping list.txt", "w");
int end= 0; //have you finished writing the articles
char article[80]; //the article you want to buy
int n; //quantity
while(!end){
printf("What do you need to buy? ");
fgets(article, 80, stdin);
article[strlen(article)- 1]= '\0';
fprintf(fp, "%s ", article);
printf("How much of it? ");
scanf("%d", &n);
fprintf(fp, "%d\n", n);
printf("Are you done? (1= Yes, 0= No) ");
scanf("%d%*c", &end);
}
fclose(fp);
}
It should print out on the file (which is created and remains empty) your input. There is no error message
I've resolved the problem by simply specifying the absolute path in fopen
Ive recently begun learning C and am trying to write a password data protection program. Im writing a function which should test to see if a file, password.txt exists if it doesnt it will get a null value and then ask the user to set a master password and to repeat. However it doesnt allow the user to repeat the password. Any tips? - Cheers (Keep in mind just C not C++)
/*Headers*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_LENGTH 99
int main(void){
/*Variable Declaration*/
char password[] = "Lakaka";
masterPassword();
printf("Welcome to Fort-Knox.");
getchar();
return 0;
}
int masterPassword(void){
/*Password Comparison Variables*/
char password[MAX_LENGTH];
char password1[MAX_LENGTH];
FILE*fp;
if (fp == NULL){
printf("Choose a master password:\n");
scanf("%c", password);
printf("Please repeat password:\n");
scanf("%c", password1);
if (password == password1){
printf("Password Accepted.");
fp = fopen("password.txt", "w+");
printf("File Created");
fclose(fp);
return 0;
}
}
}
Use %s not %c as format specifier, when reading a string. %c only reads a single character.
Your formatting specifier is wrong.
This is also wrong:
if (password == password1)
this will only compare the arrays converted to pointers. You need to compare character-by-character, by calling strcmp():
if( strcmp(password, password1) == 0 )
{
printf("match!\n");
}
use "%s" instead of "%c"
%c is for only 1 character
%s is for string
scanf("%s", password);
scanf("%s", password1);
you need to do
scanf("%s", password);
and to compare use :
strncmp(password,password1,MAX_LENGTH)
it´s always more safe :)...
I'm creating a program that asks the user to input a word. The word is then compared with a word in a text file. If correct, I want the user to input another word which should correspond with the next word in the text file and this should loop until the end of the file. I'm having trouble with the loop to the end of the file. Could someone please review my code and give me a few pointers? thanks so much
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}
i made some suggestions about scanf_s and fscanf_s, if they are available, use them. But still, i am wondering why they are still teaching bad code in schools? I would not suggest to use *scanf* functions at all. Further reading: uncontrolled format string
Move the fscanf call that reads from the file to a function that returns the next word
loop for user input, only calling the function outlined above when you need to advance to the next word in the file (when the user inputs the correct thing)