I'm currently trying to use a struct "test", to print an array of 10 random things the user inputs. The program compiles, and runs, however after I enter the final 10th item, the .txt file only contains the first element I've entered.I've tried moving the area of which the fprintf function is called, but my attempt at that was to no avail. Any input on this would be much appreciated.
Continues to only print the first element (i.e what I type first)
#include <stdio.h>
#include <ncurses.h>
//EDIT NEW CODE UPDATED, BUT IT STILL ONLY PRINTS THE FIRST ELEMENT\\
typedef struct test
{
char test[10];
}test;
int main(void)
{
initscr();
cbreak();
noecho();
testFunction();
}
int testFunction()
{
int i;
test inputString[10];
FILE *f = fopen("file.txt", "w");
for(i=0;i<10;i++)
{
mvprintw(50,50,"Please enter a 10 things");
getstr(inputString[i].test);
fprintf(f, "%s\n", inputString[i].test);
}
fclose(f);
}
You're closing your file inside the loop, and not opening it again.
Move the fclose() call to outside your loop.
By the way, you don't need the while loop.
Related
I am writing a program that inputs two text files
inputtxt1,
inputtxt2
and output
outputtxt file
In these two files information such as
input txt1
S00111111 5 6-Jul-19 09-Aug-19
S00800000 4 1-Jul-19 30-Aug-19
S00000000 1 1-Jul-19 30-Aug-19
input txt2
S00111111 3 6-Jul-19 09-Aug-19
S00222222 1 20-Jul-19 30-Aug-19
S00000000 1 1-Jul-19 30-Aug-19
I am writing a program to input these two txt files and output the differences in SQL queries and the values inside the bracket will change depends on the differences from these text files.
DELETE FROM TABLE WHERE TABLE=[] AND TABLE=[]
INSERT INTO TABLE (TABLE1,TABLE2,TABLE3,TABLE4) VALUES ([ ],[],'[2019-08-30] 00:00:00','[2019-07-01] 00:00:00');
DELETE FROM TABLE WHERE TABLE=[] AND TABLE=[4]
INSERT INTO TABLE (TABLE,TABLE) VALUES ([],[4]);
I wrote my draft in C so what I did id basically a while loop to read each of the line of the first file and each of the line of the second file and output the query.
Here are my two questions:
First it, unfortunately, output the file SQL 3 times, I think there is something wrong with my while loop.
Secondly, how would I make the program detect that specific character from specific line need to be printed in the query for example number 5 in the first line would detect and add to the value of one of the tables in the query.
/* This program will input two text files, output a text file with the differences*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *in1, *in2, *out;
int a, b;
void main (void)
{
int c;
char* singleline [33];
char* singleline2 [33];
in1 = fopen ("inputtest1.txt", "r"); /* reads from the first file */
in2 = fopen ("inputtest2.txt", "r"); /* reads from the second file */
out = fopen ("outputtest3", "w"); /* writes out put to this file */
// Menu //
printf ("TSC Support Program\n\n");
printf ("This program compare the two files and output the differences in SQL quries \n");
// if the file is empty or something went wrong!
if (in1 == NULL || in2 == NULL)
{
printf("********************Can Not Read File !**************************");
}
else
{
// Checking Every line in the first text file if it equals to the first line of the text file
while (!feof(in1)&&!feof(in2))
{
// a = getc(in1);
// b = getc(in2);
a = fgets(singleline, 33,in1);
b = fgets(singleline2, 33,in2);
if (a!=b)
{
printf("\n SQL will be printed\n");
fprintf (out,
"\n DELETE FROM BADGELINK WHERE BADGEKEY=[27] AND ACCLVLID=75"
"\nINSERT INTO BADGELINK (BADGEKEY,ACCLVLID,ACTIVATE,DEACTIVATE) VALUES ([27],75,'[2010-08-24] 00:00:00','[2010-12-17] 00:00:00'); \n"
"\n DELETE FROM BADGE WHERE BADGEKEY=[27] AND ISSUECODE=[75]"
"\nINSERT INTO BADGE (BADGEKEY,ISSUECODE) VALUES ([27],[1]);\n"
);
}
else
{
printf("Something went wrong");
}
}
}
fclose(in1);
fclose(in2);
fclose(out);
}
It prints the output 5 times
and then it says something went wrong. I am unsure what went wrong.
if (a != b) does not do what you think it is doing. Check strncmp() or memcmp() library functions.
But if you want to find out the first different character in two strings, the code below would do it for you.
Not tested properly, so take it as a quick prototype.
#include <stdio.h>
int strdiff(char *s1, char *s2){
char *p1 = s1;
while(*s1++ == *s2++)
;
if (s1 != s2)
return --s1-p1; /* we have s1++ in the while loop */
return -1;
}
int main(){
char *s1="S00111111 5 6-Jul-19 09-Aug-19";
char *s2="S00111111 3 6-Jul-19 09-Aug-19";
int i = strdiff(s1,s2);
printf("%d %c\n",i, s1[i]);
return 0;
}
Mind you, comparing two files line by line may turn out to be a bigger mission than it sounds if the two files you are comparing do not have exactly the same lines (with minor differences of course).
I am trying to get name of the input, output, and data files from the array for further processing. However, I am getting a weird error or problem. So, my program is not reaching the for loop. It does not even print the statement before the for loop. However, I tried using the debugger and the program is correctly printing step by step. So, when I run it does not print and when I debug step by step it prints. That is Weird!
char *method;
method=malloc(25);
method=NULL;
char *dataFileName;
char *inputMethod;
inputMethod=malloc(25);
inputMethod=NULL;
char *inputFileName;
char *outputMethod;
outputMethod=malloc(25);
outputMethod=NULL;
char *outputFileName;
char *commandArray[]={"if=q.txt","of=output.txt"};
char**args=(char**) malloc(sizeof(char*)*256);
args=commandArray;
int i;
printf("Before second for");
for(i=0;i<2;i++)
{
printf("I am here");
if(*args[i]=='d')
{
method=strtok_r(args[i],"=",&dataFileName);
printf("The method given is %s",method);
printf("Data File Name is %s",dataFileName);
}
else if(*args[i]=='o')
{
outputMethod=strtok_r(args[i],"=",&outputFileName);
printf("The output method given is %s",outputMethod);
printf("output File Name is %s",outputFileName);
}
else
{
inputMethod=strtok_r(args[i],"=",&inputFileName);
printf("The input method given is %s",inputMethod);
printf("Input File Name is %s",inputFileName);
}
}
if(method==NULL)
{
dataFileName=malloc(256);
printf("Please Enter A File Name");
scanf("%255s",dataFileName);
printf("%s",dataFileName);
}
if((inputMethod==NULL)||(outputMethod==NULL) )
{
char* array[]={"stdin","stdout"};
if(inputMethod==NULL)
inputMethod=array[0];
if(outputMethod==NULL)
outputMethod=array[1];
}
I am developing using Netbeans in C. The above code is written inside main. Thanks!
i intentionally left the previous answer because understanding memory allocation is trivial in programming in c specially. and as i see you have a big issue with that.
but still you have issue in nearly every thing. in my actual answer, i will try to simplify you how to use strtok, to split string and parse it. i guess this is the second main problem with your code.
the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char commandArray[][256]={
"if=q.txt",
"of=output.txt"
};
char infile[256], outfile[256];
for(int i=0; i<2;i++){
char *ptr,*cmd;
cmd=commandArray[i];
ptr=NULL;
printf("parsing command '%s'\n",cmd);
cmd=strtok(cmd,"=");
ptr=strtok(NULL,"=");
if(!cmd){
printf("Error parsing the string '%s'\n",commandArray[i]);
exit(1);
}
if (strcmp(cmd,"if")==0){
strcpy(infile,ptr);
}
else if (strcmp(cmd,"of")==0){
strcpy(outfile,ptr);
}
else{
printf("unknow token '%s'\n",cmd);
exit(1);
}
}
printf(
"\n\n"
"input file: '%s'\n"
"output file: '%s'\n"
"\n\n",
infile,outfile);
return 0;
}
the main problem is this:
char *method;
method=malloc(25);//allocating space for 25 char
method=NULL; // throwing up the allocation without freeing it;
// now the allocation is lost
// now method is useless (it is null)
I'm a bit green in C and whole programming so I need help on task.
My goal is to read text file with random words(strings) and if there are any numbers in strings, change them to first letter of that word/string. Example: "He99llo Im N3w Her3" > "HeHHllo Im NNw HerH"
Questions: 1. How can I read separate strings from text file?
2. How can I get first letter (not number) from seperate strings?
By the way, I've wrote code, that takes only first char of text file and changes numbers into it, whenever it's number or not, but I dont know how to add code here...
EDIT: Here's the code written code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int Change(FILE *Reading, FILE *Writing){ /*Reads from file and changes numbers into first character of file*/
int FirstLetter, letter;
Reading = fopen("C:\\Users\\Rimas\\Desktop\\read.txt", "r");
Writing = fopen("C:\\Users\\Rimas\\Desktop\\write.txt", "w");
if (Writing == NULL) {
printf("I couldn't open write.txt for writing.\n");
exit(0);
}
FirstLetter = getc(Reading);
if (Reading){
fprintf(Writing, "%c", FirstLetter);
while ((letter = getc(Reading)) != EOF){
if (isdigit(letter)){
letter = FirstLetter;
}
fprintf(Writing, "%c", letter);
}
}
fclose(Reading);
fclose(Writing);
return 0;
}
int main() {
FILE *Reading;
FILE *Writing;
Change(Reading, Writing);
return 0;
}
Here's some logic to help you:
Write a function that accepts a string and converts it as you described. Do this first. And test it well because it is the fundamental part of the program.
Now you want to read a text file from main and simply display each word on screen in it's own line. This is to help you understand how to read words from a file. I would use fscanf for this. Make sure you can read the entire text file and it doesn't crash
Now right before printing the word that read in form step 2, call the function from step 1. This will alter the word and when you print you should get the correct results.
I'm trying to check a directory for a file. I've done that properly. But I'm having trouble for exceptions--> when the file is not there. Here's what I am wanting to do: I 'd like to check for the file, if it exists, then exit the loop. If the file does not exist, then sleep. After sleeping for 3 seconds, check for the file again. Repeat until the file is found then return to main() and print "Hello everyone".
Currently, if the file is missing and i put the file into this directory while the program is running, it never recognizes the new file until i stop the program then start it back up. I want the program to check for the file again after sleep.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <unistd.h>
#define MYFILE "/Users/stackoverflow/Documents/fileabc123"
int checkfile() {
FILE *pFile;
pFile = fopen(MYFILE,"r");
char file_string[40];
int repeat = 0;
while( repeat < 1) {
if (pFile!=NULL) {
fgets (file_string,36,pFile);
fclose (pFile);
printf("%s\n", file_string);
repeat = 1 ;
}
if (pFile ==NULL) {
printf("Machine cannot read system file. \n");
sleep(3);
}
}
}
int main (int argc, char ** argv) {
checkfile();
printf("Hello everyone\n");
return 0;
}
You need to put the fopen in the loop.
if ((pFile = fopen(MYFILE, "r")) != NULL) {
// read it
}
else {
printf("Failed opening");
}
The error is in the loop.
you simply aren't trying to open the file again :)
this give you 2 error:
1. if you put the file it is not seen, as the program does not try to open it
2. if the file is present, you read it, then you close it, leaving an INVALID file descriptr but that is NOT null
this mean next loop you will try to read an invalid file descriptor. It is like reading/writing value with a overflow index from an array, or from a free() pointer.
You will almost always have the right value.. until that ram is reallocated.
so:
1. you have to try to open a file, until you get a valid file descriptor.
2. close will not change pointer value. It simply can't, think about it.
if you whant to change the value of somthing, you have to give it's address. A pointer is the adress of somthing. So File* is pointing to a File, but if you want to change the address pointed by File*, you need it's address (&pFile), just like a scanf :)
How do I read in an external file and then either print the whole text or selected lines?
FILE *fp;
fp=fopen("c:\\students.txt", "r");
I understand that reads the file but after that I am lost. Help please!!!
Do I need to read in binary or is text file acceptable?
You get a pointer to the file stream with fopen()
fread() will only return the amount of actual data that the program
could find inside your .txt file - It's very misleading. The main use is getting the number of elements for your loops. You can upload a file into your program, and print it on the screen without ever touching this function, if you know exactly what the file should already have. Only use this if you don't know what's in your file.
getline() is your go-to for printing out a specific line. No way around this one, and you'll need the specific library for it.
Here's an Example Code I wrote while doing a self-study on this, just showing how each of these are used, and printing out on BOTH the program, and a separate txt file outside the program. It doesn't have getline() however.
/*
Goals:
Create an array of 5 values
Input 5 vales from a pre-created file, into the new array
Print out the 5 values into another file.
Close the file.
*/
#include <stdio.h>
#include <stdlib.h>
#define DATAFILE "E:/Data.txt"
#define REPORT "E:/Report.txt"
//prototypes
FILE *Open_File();
void Consolodate_Array(int a_array[], FILE *file_pointer);
void Print_File(int a_array[], FILE *report_pointer);
void end_function(FILE *file_pointer, FILE *report_pointer);
int main(int argc, char *argv[])
{
int array[5];
FILE *Datatext = Open_File();
//Declared "Datatext" to be equal to Open_File's Return value.
//FILE itself is like Int, Double, Float, ect.
FILE *ReportText = fopen(REPORT, "w");
//Did the same as above, just not in a separate function. This gives us a
//Pointer to the REPORT.txt file, in write mode instead of read mode.
Consolodate_Array(array, Datatext);
Print_File(array, ReportText);
end_function(Datatext, ReportText);
system("PAUSE");
return 0;
}
/*----------------------------------------------------------------------*/
//This function should open the file and pass a pointer
FILE *Open_File()
{
return fopen(DATAFILE, "rb");
}
/*----------------------------------------------------------------------*/
//This function should input the variables gotten for the file, into the array
void Consolodate_Array(int a_array[], FILE *file_pointer)
{
for(int i=0; i<5; i++)
fscanf(file_pointer, "%i", &a_array[i]);
}
/*----------------------------------------------------------------------*/
//This function prints out the values into the second file, & at us too.
void Print_File(int a_array[], FILE *report_pointer)
{
for(int i=0; i<5; i++)
{
printf("%i\n", a_array[i]);
fprintf(report_pointer, "%i\n", a_array[i]);
}
}
/*----------------------------------------------------------------------*/
//This function closes the file.
void end_function(FILE *file_pointer, FILE *report_pointer)
{
fclose(file_pointer);
fclose(report_pointer);
//closes both files we worked on.
}